title,body,link,tags,view_count,is_answered,score,answer_count
Junit integration testing,"<p>I need help writing a unit test for class <code>NotificationHandler</code>. so I made <code>NotificationHandlerTest</code> (using junit4) but I don't know how to determine what I should expect as a result versus what the actual result is, so one or more simple test's (for some of its methods) would help me a lot!</p>

<pre><code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
class NotificationHandler {

    private static Logger LOG = LoggerFactory.getLogger(NotificationHandler.class);

    @Autowired
    private NotificationRoutingRepository routingRepository;

    @Autowired
    private SendNotificationGateway gateway;

    @Autowired
    private AccessService accessService;

    @Autowired
    private EndpointService endpointService;

    @ServiceActivator(inputChannel = Channels.ASSET_MODIFIED_CHANNEL, poller = @Poller(""assetModifiedPoller""), outputChannel = Channels.NULL_CHANNEL)
    public Message&lt;?&gt; handle(Message&lt;EventMessage&gt; message) {
        final EventMessage event = message.getPayload();

        LOG.debug(""Generate notification messages: {}, {}"", event.getOriginType(), event.getType());

        routingRepository.findByOriginTypeAndEventType(event.getOriginType(), event.getType()).stream()
                .filter(routing -&gt; routing.getOriginId() == null || routing.getOriginId() == event.getOriginId())
                .map(routing -&gt; getNotificationMessages(event, routing))
                .flatMap(List::stream)
                .forEach(notificationMessage -&gt; {
                    LOG.debug(""Sending message {}"", notificationMessage);
                    gateway.send(notificationMessage);
                });

        return message;
    }enter code here
    enter code here`enter code here`
    private List&lt;NotificationMessage&gt; getNotificationMessages(EventMessage event, NotificationRouting routing) {
        switch (routing.getDestinationType()) {
            case ""USERS"":
                LOG.trace(""Getting endpoints for users"");
                return getEndpointsByUsers(routing, event.getOrigin(), event.getOriginType()).stream()
                        .map(endpoint -&gt; new NotificationMessage(event.getOriginType(), event.getOrigin(), endpoint))
                        .collect(Collectors.toList());
            default:
                LOG.trace(""Getting default endpoints"");
                return getEndpoints(routing, event.getOrigin(), event.getOriginType()).stream()
                        .map(endpoint -&gt; new NotificationMessage(event.getOriginType(), event.getOrigin(), endpoint))
                        .collect(Collectors.toList());
        }
    }

    private List&lt;Endpoint&gt; getEndpoints(NotificationRouting routing, Object origin, String originType) {
        final Asset asset = getAssetForObject(origin, originType);

        final List&lt;Long&gt; userIds = accessService.list(asset).stream()
                .map(ResourceAccess::getUser)
                .map(AbstractEntity::getId)
                .collect(Collectors.toList());

        userIds.add(asset.getCreatorId());

        LOG.trace(""getEndpoints usersIds {}"", userIds);

        final List&lt;Endpoint&gt; endpoints = endpointService.getEndpoints(userIds, routing.getEndpointType());
        LOG.trace(""Endpoints {}"", endpoints.stream().map(Endpoint::getId).collect(Collectors.toList()));
        return endpoints;
    }

    private List&lt;Endpoint&gt; getEndpointsByUsers(NotificationRouting routing, Object origin, String originType) {
        final Asset asset = getAssetForObject(origin, originType);

        final List&lt;Long&gt; userIds = accessService.list(asset).stream()
                .map(ResourceAccess::getUser)
                .map(AbstractEntity::getId)
                .filter(routing.getDestinations()::contains)
                .collect(Collectors.toList());

        routing.setDestinations(userIds);
        routingRepository.save(routing);

        LOG.trace(""getEndpointsByUsers usersIds {}"", userIds);

        final List&lt;Endpoint&gt; endpoints = endpointService.getEndpoints(userIds, routing.getEndpointType());
        LOG.trace(""Endpoints {}"", endpoints.stream().map(Endpoint::getId).collect(Collectors.toList()));
        return endpoints;
    }

    private Asset getAssetForObject(Object origin, String originType) {
        switch (originType) {
            case EventMessage.POINT:
                return (Point) origin;
            case EventMessage.FEED:
                return ((Feed) origin).getPoint();
            case EventMessage.ACTUATOR:
                return ((Actuator)origin).getPoint();
            case EventMessage.DEVICE:
                return (Device) origin;
            case EventMessage.ALARM:
                return ((Alarm) origin).getPoint();
            default:
                throw new IllegalArgumentException(""Unsupported type: "" + originType);
        }
    }
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/47138065/junit-integration-testing,"['java', 'unit-testing', 'junit', 'dependency-injection', 'constructor-injection']",1001,TRUE,0,1
JMS integration testing,"<p>I am trying to write an integration test for JMS service which looks like something like this.</p>

<pre><code> @JmsListener(destination = ""mailbox"", containerFactory = ""myFactory"")
 public void receiveMessage(Email message) throws InterruptedException {
    try {
        sendEmail(message);
    }catch (Exception e){
        LOGGER.log(Level.SEVERE,""Failed to deliver email"",e);
        Thread.sleep(TimeUnit.SECONDS.toSeconds(Optional.of(retryInterval).orElse(5)));
        throw e;
    }
}

private void sendEmail(Email message){
    ...............
}
</code></pre>

<p>First of all, can I mock this some how? I tried mocking it, but when I send a message the spring boot application is calling the actual JMS bean not the mock one. Seems like this is not possible. 
Even if this is not possible, can I at least aoutowire the bean and somehow check if the receiveMessage method is being invoked. Furthermore, if it is being invoked, the sendEmail part should be faked so that it does not do any work. I have a few ideas such as creating a subclass for testing, but not happy with either of them. So wanted to if you can suggest me a better work around?</p>
",https://stackoverflow.com/questions/45514864/jms-integration-testing,"['unit-testing', 'mocking', 'mockito', 'integration-testing', 'spring-jms']",3434,TRUE,0,1
Integration testing Android,"<p>I'm new to testing on Android. I see a lot of articles and tutorial about unit testing and with end-to-end testing (with espresso). It's ok. But what about integration testing ?</p>

<p>For the exemple, I use Firebase Database for my app. Is it possible to do this kind of test in the instrumentation test :</p>

<pre><code>@Test
public void tryFirebaseTest() throws FieldRequiredException, InvalidPhoneException, InvalidEmailException, InterruptedException {

    UserManager userManager = new UserManager(new FIRUserStorage(FirebaseDatabase.getInstance().getReference()));
    userManager.createUser(""test@test.com"", ""test"", ""+4778787"", """", new CreateUserCallback() {
        @Override
        public void userCreated(User user) {
            assertNotNull(user);
        }

        @Override
        public void userExistError() {
            fail();
        }

        @Override
        public void userDatabaseError(String errorMessage) {
            fail();
        }
 });

}
</code></pre>

<p>In this case, the test don't get in the callback.</p>
",https://stackoverflow.com/questions/41585530/integration-testing-android,"['android', 'unit-testing', 'testing', 'integration-testing', 'android-testing']",547,FALSE,0,1
Integration testing garbage data,"<p>I have set up integration testing using MSTest. My integration tests create fake data and insert them into the database (real dependencies). For every business object, I have a method like this, which creates a ""Fake"" and inserts it into the db: </p>

<pre><code>public static EventAction Mock()
{
    EventAction action = Fixture.Build&lt;EventAction&gt;().Create();
    action.Add(false);
    AddCleanupAction(action.Delete);
    AppendLog(""EventAction was created."");
    return action;
}
</code></pre>

<p>I clean up all the fakes in [AssemblyCleanup]:</p>

<pre><code>public static void CleanupAllMockData()
{
    foreach (Action action in CleanUpActions)
    {
        try
        {
            action();
        }
        catch
        {
            AppendLog($""Failed to clean up {action.GetType()}. It is possible that it was already cleaned up by parent objects."");
        }
    }
}
</code></pre>

<p>Now, I have a big problem. In my continuous integration environment (TeamCity), we have a separate database for testing, and it cleans itself after every test run, but on my local environment, the integration tests point to my local database. Now, If I cancel the test run for any reason, that leaves a bunch of garbage data in my local database, because CleanupAllMockData() never gets called.</p>

<p>What is the best way to handle this? I couldn't find a way to intercept the test cancellation in MSTest. </p>
",https://stackoverflow.com/questions/47795561/integration-testing-garbage-data,"['c#', 'integration-testing', 'mstest', 'dummy-data']",402,TRUE,4,1
Dropwizard integration testing with Testcontainers,"<p>I'm trying to run dropwizard's integration tests against a dockered database.</p>

<ul>
<li><a href=""http://www.dropwizard.io/1.1.2/docs/"" rel=""noreferrer"">Dropwizard</a></li>
<li><a href=""https://github.com/testcontainers/testcontainers-java"" rel=""noreferrer"">Testcontainers</a></li>
</ul>

<p>What I've tried:</p>

<pre><code>@ClassRule
public static final PostgreSQLContainer postgres = new PostgreSQLContainer();

@ClassRule
    public final DropwizardAppRule&lt;Configuration&gt; RULE = new DropwizardAppRule&lt;&gt;(
            Application.class,
            CONFIG_PATH,
            ConfigOverride.config(""dataSourceFactory.url"", postgres.getJdbcUrl()),
            ConfigOverride.config(""dataSourceFactory.user"", postgres.getUsername()),
            ConfigOverride.config(""dataSourceFactory.password"", postgres.getPassword())
    );
</code></pre>

<p>I get <code>Caused by: java.lang.IllegalStateException: Mapped port can only be obtained after the container is started</code></p>

<p>Chaining these together does not work either</p>

<pre><code>@ClassRule
    public static TestRule chain = RuleChain.outerRule(postgres = new PostgreSQLContainer())
            .around(RULE = new DropwizardAppRule&lt;&gt;(
                    Application.class,
                    CONFIG_PATH,
                    ConfigOverride.config(""dataSourceFactory.url"", postgres.getJdbcUrl()),
                    ConfigOverride.config(""dataSourceFactory.user"", postgres.getUsername()),
                    ConfigOverride.config(""dataSourceFactory.password"", postgres.getPassword())
            ));
</code></pre>

<p>Finally this works, but as I understand it runs the new DropwizardAppRule for every test and this is <strong>not good</strong>...</p>

<pre><code>@ClassRule
public static final PostgreSQLContainer postgres = new PostgreSQLContainer();

@Rule
    public final DropwizardAppRule&lt;Configuration&gt; RULE = new DropwizardAppRule&lt;&gt;(
            Application.class,
            CONFIG_PATH,
            ConfigOverride.config(""dataSourceFactory.url"", postgres.getJdbcUrl()),
            ConfigOverride.config(""dataSourceFactory.user"", postgres.getUsername()),
            ConfigOverride.config(""dataSourceFactory.password"", postgres.getPassword())
    );
</code></pre>

<p>So how can I chain the rules such that PostgreSQLContainer is initiated first and container has started before creating the DropwizardAppRule?</p>
",https://stackoverflow.com/questions/45096498/dropwizard-integration-testing-with-testcontainers,"['dropwizard', 'testcontainers']",2542,TRUE,9,1
Integration testing IdentityServer4 repository,"<p>I am using the repository pattern within my implementation, and adding an ApiResourceRepository.  Here is a sample of that:</p>

<pre><code>public class ApiResourceRepository : IApiResourceRepository
{
    private readonly IServiceProvider _serviceProvider;

    public ApiResourceRepository(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
        _dbSettings = dbSettings;
    }

    public async Task&lt;ApiResource&gt; Get(int id)
    {
        ApiResource result;

        using (var serviceScope = _serviceProvider.CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService&lt;ConfigurationDbContext&gt;();
            result = await
                context.ApiResources
                .Include(x =&gt; x.Scopes)
                .Include(x =&gt; x.UserClaims)
                .FirstOrDefaultAsync(x =&gt; x.Id == id);
        }

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

<p>Is this the suggested way of obtaining/working with a <code>ConfigurationDbContext</code>?</p>

<p>I am also struggling with my integration tests, because it seems like I would have to mock an IServiceProvider that can provide an instance of the <code>ConfigurationDbContext</code>?  How do you address these concerns?</p>
",https://stackoverflow.com/questions/44335903/integration-testing-identityserver4-repository,"['c#', '.net', 'asp.net-core', 'identityserver4']",178,FALSE,1,0
Grails async integration testing,"<p>I've a Grails 2.5.6 project with a rest controller in which I create n async tasks each of them invoking a method in a service like this:</p>

<pre><code>// MyController
...
def statuses = ['where', 'ownership', 'store']
def tasks = statuses.collect { st -&gt;
    task {
        return myService.invokeMethod(st, [aDomain, data])
    }
}
def props = waitAll(tasks)
...


// MyService
...
store(aDomain, data) {
    ...
    def store = Store.get(data.store)
    ...
}
</code></pre>

<p>If I execute the application, the Store is correctly found in the database.</p>

<p>I've also created an integration test. To avoid conflicts with existing data in the database I create a new <code>Store</code> during the test:</p>

<pre><code>// Integration test (simplified)
....
def store = new Store(....)
store.save(flush: true)
...
def json = [store: store.id] as JSON
...
controller.request.content = params.toString()
controller.request.method = ""POST""
controller.update()
...
</code></pre>

<p>If I execute the tests, the new store created is not found in the service and the test fails.
I've verified the situation in some points of the application and found that:
- if I search the store in the controller (before or after the tasks are executed), it is found
- if I list all the stores in the service method the new store doesn't exist.</p>

<p>I suppose that this behaviour is due to how hibernate session is handled during tests but I don't know how to solve it.
Any suggestion is welcome.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/45590692/grails-async-integration-testing,['grails'],156,TRUE,0,1
Integration Testing CakePHP 3,"<p>I am doing Integration testing in CakePHP 3 following is Unit Test Function.</p>

<pre><code>public function testlogin()
    {
        $this-&gt;post('/users/login', ['username' =&gt; 'test', 'password' =&gt; 'test']);

        $this-&gt;assertRedirect(['controller' =&gt; 'Users', 'action' =&gt; 'index']);
    }
</code></pre>

<p>When I run Unit Test then it gives me 'No location header set' and TestCase is failing.</p>

<p>so I don't know which header I have to set.</p>

<p>Anyone Tell me which header I have to set here?</p>
",https://stackoverflow.com/questions/46482394/integration-testing-cakephp-3,"['php', 'unit-testing', 'cakephp', 'phpunit', 'cakephp-3.0']",326,FALSE,0,1
Integration testing in Symfony,"<p>I'm writing a reusable bundle and want to carry out an integration testing of this bundle with the hosting app. The problem is that Symfony doesn't call neither the <code>DependencyInjection\Extension::load</code> nor <code>DependencyInjection\Configuration::getConfigTreeBuilder</code> method of my bundle, therefore the bundle's service configuration is not loaded and the services are not constructed properly. How can I get Symfony to load everything in tests, as if it was a real request? </p>

<p>Here is my test:</p>

<pre><code>namespace Tests\AclAgentBundle;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class IntegrationTest extends KernelTestCase
{
    public function testAgentExistence()
    {
        $container = static::bootKernel()-&gt;getContainer();

        $service = $container-&gt;get('test.Foo\Bar\Baz');

     //...assertions...
}
</code></pre>

<p><code>test.Foo\Bar\Baz</code> is an alias of a service, declared in the hosting app's config like</p>

<pre><code>services:
    test.Foo\Bar\Baz: '@Foo\Bar\Baz'
</code></pre>

<p>used to fetch the service via the container's <code>get</code> method in tests.</p>
",https://stackoverflow.com/questions/47230402/integration-testing-in-symfony,"['php', 'symfony', 'unit-testing', 'integration-testing']",682,FALSE,0,1
Spring Boot Integration Testing,"<p>I have been trying to write a integration test for a small Spring boot Project that I have written but for some reason seem unable to get integration tests to work.  Here is what I am trying to do:</p>

<pre><code>package au.azzmosphere.integration;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {IntegrationTestConfiguration.class})
public class TestIntegration1 {
    @Test
    public void testDummy() {

    }
}
</code></pre>

<p>the configuration class has the following:</p>

<pre><code>package au.azzmosphere.integration;

import au.azzmosphere.configuration.RobotAppConfig;
import org.springframework.context.annotation.Configuration;

@Configuration
public class IntegrationTestConfiguration extends RobotAppConfig {
}
</code></pre>

<p>The code is consistently getting the following errors when I try to run the Integration Test from IntelliJ</p>

<pre><code>14:54:01.537 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class au.azzmosphere.integration.TestIntegration1].
14:54:01.542 [main] INFO org.springframework.test.context.TestContext - @ContextConfiguration not found for class [class au.azzmosphere.integration.TestIntegration1].
14:54:01.549 [main] INFO org.springframework.test.context.TestContextManager - @TestExecutionListeners is not present for class [class au.azzmosphere.integration.TestIntegration1]: using defaults.
</code></pre>

<p>From gradle the following is returned</p>

<pre><code>au.azzmosphere.integration.TestIntegration1 &gt; initializationError FAILED
    java.lang.NoClassDefFoundError
        Caused by: java.lang.ClassNotFoundException
</code></pre>

<p>The full stack trace is</p>

<pre><code>java.lang.NoClassDefFoundError: org/springframework/transaction/TransactionDefinition

    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
    at java.lang.Class.getConstructor0(Class.java:3075)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:102)
    at org.springframework.test.context.TestContextManager.retrieveTestExecutionListeners(TestContextManager.java:171)
    at org.springframework.test.context.TestContextManager.&lt;init&gt;(TestContextManager.java:108)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:107)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.&lt;init&gt;(SpringJUnit4ClassRunner.java:79)
    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:423)
    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 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    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.ClassNotFoundException: org.springframework.transaction.TransactionDefinition
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 23 more
</code></pre>
",https://stackoverflow.com/questions/46030528/spring-boot-integration-testing,"['java', 'spring-boot', 'spring-boot-test']",1134,FALSE,0,1
Integration testing with Junit,"<p>I have a million requests and responses in a mongo collection. I have written a parameterized JUnit to load the request and run it against another server and compare the response with the mongo collection response. </p>

<p>The issue is, this is a good solution for a few 1000 documents in collection, but is not a scalable solution. </p>

<p>Is there any suggestion or good api which extends JUNit to help me test a million records. 
Also, I would like to have each of the record to be a unit test case, so that it shows finally how many has passed. </p>

<p>Here is a snippet using Junit5 : </p>

<pre><code>@TestFactory
Stream&lt;DynamicTest&gt; test1() throws Exception {
    List&lt;MyClass&gt; data = setUp();
    return data.stream().map(d -&gt; DynamicTest.dynamicTest(""TC""+d.toString(), () -&gt; assertTrue(doTest(d))));
}

public boolean doTest(MyClass mc) {
//actual test
}
</code></pre>

<p>Issue with this code is this line</p>

<pre><code> List&lt;MyClass&gt; data = setUp();
</code></pre>

<p>It tries to load all the testcase from the mongo and I am not sure how to split this up. Let me know if a Junit4 way of code is needed. </p>
",https://stackoverflow.com/questions/46126822/integration-testing-with-junit,"['junit', 'integration-testing']",55,FALSE,0,0
C# Integration testing with rollback,"<p>I try integration testing with rollback. I use SQL server. My setup, which I took from this <a href=""https://stackoverflow.com/a/3538035/3246527"">topic</a>, looks like this: </p>

<pre><code>private TransactionScope scope;

[TestInitialize]
public void Initialize()
{
    this.scope = new TransactionScope();
}

[TestCleanup]
public void TestCleanup()
{
    this.scope.Dispose();
}
</code></pre>

<p>Testing method:</p>

<pre><code>var newUser = new UserDetailModel();
newUser.Id = 1;
newUser.Email = ""test@test.cz"";
newUser.FirstName = ""Test"";
newUser.LastName = ""User"";
newUser.UserName = ""test.user"";
await userManager.AddAsync(newUser);
</code></pre>

<p>There shouldn't be a new user in db after the test is completed, but I have new user in db even test is finished. I even tried the same method with <em>Database.BeginTransaction()</em>:</p>

<pre><code>using (var transaction = unitOfWork.GetDbContext().Database.BeginTransaction())
{
    var newUser = new UserDetailModel();
    newUser.Id = 1;
    newUser.Email = ""test@test.cz"";
    newUser.FirstName = ""Test"";
    newUser.LastName = ""User"";
    newUser.UserName = ""test.user"";
    await userManager.AddAsync(newUser);

    transaction.Rollback();
}
</code></pre>

<p>Rollback doesn't work either.</p>
",https://stackoverflow.com/questions/45694542/c-integration-testing-with-rollback,"['c#', 'integration-testing']",2400,TRUE,3,1
ASP.NET MVC WebApi Integration testing,"<p>I am trying to write integration tests for my ASP.NET MVC WebApi application. I am using <code>MvcIntegrationTestFramework</code> described <a href=""http://blog.stevensanderson.com/2009/06/11/integration-testing-your-aspnet-mvc-application/"" rel=""nofollow noreferrer"">here</a>.</p>

<p>I have test class for my controller as below:</p>

<pre><code>public class UsersControllerTests
{
    private AppHost appHost;

    public UsersControllerTests()
    {
        appHost = AppHost.Simulate(""MyApplication"");
    }

    [Test]
    public void given_valid_user_name_should_exist()
    {
        appHost.Start(browsingSession =&gt;
        {
            var userName = ""name"";
            var response = browsingSession.Get($""users/{userName}"");

            var user = JsonConvert.DeserializeObject&lt;UserDto&gt;(response.ResponseText);
            user.UserName.ShouldBeEquivalentTo(userName);

            Assert.IsTrue(response.IsSuccess);
        });
    }
}
</code></pre>

<p>My issue is that when I run the test, <code>response.ResponseText</code> returns empty string.</p>

<p>My Controller action:</p>

<pre><code>[Route(""users/{name}"")]
[HttpGet]
public async Task&lt;IHttpActionResult&gt; Get(string name)
{
    var user = await _userService.GetByNameAsync(name);
    if (user == null)
    {
        return NotFound();
    }

    return Json(user);
}
</code></pre>

<p>I will add that I am using <code>Unity Container</code> in my application.
Additional as described in blog post I provided, it says that I have to copy testing DLLs (<code>FluentAssertions, NUnit.Framework</code>) to the main application bin folder. Is there any work around for this?</p>

<p>One last question. I read an <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""nofollow noreferrer"">article</a></p>

<p>about integration testing for .NET Core and I wonder if I could use it in my application?</p>
",https://stackoverflow.com/questions/44920381/asp-net-mvc-webapi-integration-testing,"['c#', 'asp.net-mvc-4', 'asp.net-web-api', 'integration-testing']",738,FALSE,2,0
Integration testing with Spring Boot,"<p>Out of curiosity...
I am new to Spring Boot and I am doing some integration testing, using the newer <code>@SpringBootTest</code> annotation for the test class. </p>

<p>In the regular code (non-test code), the application has a custom initializer that allows it to load up external YAML files. </p>

<p>I wanted to make use of this in the test, so I have a <code>@ContextConfiguration</code> annotation that overrides the initializer, and likely because I added this annotation, it messes up whatever voodoo the <code>@SpringBootTest</code> is doing, so I need to add the classes parameter to give it the main <code>SpringApplication</code> so the application context is available during the test and <code>Autowired</code> beans can be found. </p>

<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ExamProcessorApplication.class, initializers = YamlFileApplicationContextInitializer.class)
@SpringBootTest
@Transactional
public class AssessmentRepositoryImplIT {
    ...
}
</code></pre>

<p>The question I have is - is providing the <code>ExamProcessorApplication.class</code> (main SpringBootApplication) in the <code>@ContextConfiguration</code> the same - more or less - as what the default behavior <code>@SpringBootTest</code> would do during its auto-discovery?  </p>

<p>A colleague and I were discussing this and the thought is that my way is actually instantiating the main application object but <code>@SpringBootTest</code> is not. Just trying to understand what's going on under the hood. </p>
",https://stackoverflow.com/questions/42384246/integration-testing-with-spring-boot,"['java', 'spring', 'spring-boot', 'spring-boot-test']",261,FALSE,1,0
Rest Data Service Integration Testing,"<p>I have a rest service that I would like to be able to test without having to write hundreds of tests. To give an overview of my service please read the following: My service accepts multiple values of data, for example:</p>

<ul>
<li>City</li>
<li>State</li>
<li>Name</li>
<li>Date</li>
<li>Color</li>
</ul>

<p>On a specific URL endpoint, i.e. <code>http://serverName:port/category/specificEndpoint</code>. With this data, the internal api runs some logic and then dynamically adds values to a query(using a velocity template) that gathers the data from a database, and then returns that information to the caller of the service in a specific format.</p>

<p>To test the responses, I have been creating tests with combinations of these values. For example:</p>

<p>Search Criteria:</p>

<ul>
<li><code>&lt;City,State&gt;</code></li>
<li><code>&lt;City&gt;</code></li>
<li><code>&lt;Name, Date, Color&gt;</code></li>
<li><code>&lt;City, State, Name, Date, Color&gt;</code></li>
</ul>

<p>I then check the responses to see if they have the values of data I am looking for. As you can see, every time I add another search criteria, the tests become larger and larger. I wanted to know if a framework or method existed to handle this sort of situation.</p>

<p>There are a few corner cases that I can test separately, but does something exist to assist in testing this service, and that can easily manipulated for future search criteria additions? A framework would be capable of testing the following combinations(Power Set) given the five search criteria shown above:</p>

<pre><code>  {},{City},{State},{ Name},{ Date},{ Color},{City,State},{City, Name},{City, Date},{City, Color},{State, Name},{State, Date},{State, Color},{ Name, Date},{ Name, Color},{ Date, Color},{City,State, Name},{City,State, Date},{City,State, Color},{City, Name, Date},{City, Name, Color},{City, Date, Color},{State, Name, Date},{State, Name, Color},{State, Date, Color},{ Name, Date, Color},{City,State, Name, Date},{City,State, Name, Color},{City,State, Date, Color},{City, Name, Date, Color},{State, Name, Date, Color},{City,State, Name, Date, Color}
</code></pre>
",https://stackoverflow.com/questions/44184618/rest-data-service-integration-testing,"['java', 'rest', 'testing', 'integration-testing', 'powerset']",44,FALSE,1,0
Spring Cloud Task Integration Testing,"<p>I’m looking for some guidance on the best way of writing integration (ie tests for entire Spring Boot Application) for Spring Cloud Task.
Based on existing documentation and samples I see two approaches for this:</p>

<p>1) Use the standard @SpringBootTest with @TestPropertySource(properties = {""spring.cloud.task.closecontext_enable=false""}
as described here </p>

<p><a href=""http://docs.spring.io/spring-cloud-task/docs/1.2.0.M2/reference/htmlsingle/#_writing_your_test"" rel=""nofollow noreferrer"">http://docs.spring.io/spring-cloud-task/docs/1.2.0.M2/reference/htmlsingle/#_writing_your_test</a></p>

<p>This seems to allow effectively only one test per test class as the task is run when the spring context is initialized ie once per test class. However 
@Autowiring of beans in the context into the test class should work to eg to check the results of the task, or examine the state of the task repository.</p>

<p>2) Use SpringApplication.run(MyTaskApplication.class, myArguments); in each test method as in the example here</p>

<p><a href=""https://github.com/spring-cloud/spring-cloud-task/blob/master/spring-cloud-task-samples/batch-job/src/test/java/io/spring/BatchJobApplicationTests.java"" rel=""nofollow noreferrer"">https://github.com/spring-cloud/spring-cloud-task/blob/master/spring-cloud-task-samples/batch-job/src/test/java/io/spring/BatchJobApplicationTests.java</a></p>

<p>This allows me to write multiple tests in the test class each with potentially different spring properties or batch job parameters.</p>

<p>The main problem I have with either approach that I can’t see how to get access eg @Autowire to beans in the context such as JdbcTemplate (eg to insert test input data for a job into an embedded db) or RestTemplate (to set up expectations using MockRestServiceServer) 
after these beans are created but BEFORE the task is run - is this possible? If not it’s hard to see how to write meaningful integration tests for tasks.</p>
",https://stackoverflow.com/questions/42998181/spring-cloud-task-integration-testing,['spring-cloud-task'],1200,FALSE,0,1
ItemReader integration testing throwing ClassCastException,"<p>I am trying to integration test an ItemReader - here is the class:</p>

<pre><code>@Slf4j
public class StudioReader implements ItemReader&lt;List&lt;Studio&gt;&gt; {

   @Setter private zoneDao zoneDao;

   @Getter @Setter private BatchContext context;

   private AreaApi areaApi = new AreaApi();

   public List&lt;Studio&gt; read() throws Exception {

      return areaApi.getStudioLocations();
  }
</code></pre>

<p>Here is my bean.xml:</p>

<pre><code>&lt;bean class=""org.springframework.batch.core.scope.StepScope"" /&gt;
&lt;bean id=""ItemReader"" class=""com.sync.studio.reader.StudioReader"" scope=""step""&gt;
   &lt;property name=""context"" ref=""BatchContext"" /&gt;
   &lt;property name=""zoneDao"" ref=""zoneDao"" /&gt;
&lt;/bean&gt;
</code></pre>

<p>And here is the test I'm trying to write:</p>

<pre><code>@ContextConfiguration(locations = {
        ""classpath:config/studio-beans.xml"",
        ""classpath:config/test-context.xml""})
@TestExecutionListeners({
        DependencyInjectionTestExecutionListener.class,
        StepScopeTestExecutionListener.class })
public class StudioSyncReaderIT extends BaseTest {

    @Autowired
    private ItemReader&lt;List&lt;Studio&gt;&gt; reader;

    public StepExecution getStepExecution() {
        JobParameters jobParameters = new JobParametersBuilder()
                .toJobParameters();
        StepExecution execution = createStepExecution(
                jobParameters);
        return execution;
    }
    @Before
    public void setUp() {
        ((ItemStream) reader).open(new ExecutionContext()); } //ClassCastException

    @Test
    @DirtiesContext
    public void testReader() throws Exception {
        assertNotNull(reader.read());
    }

    @After
    public void tearDown() {
        ((ItemStream) reader).close(); //ClassCastException
    }
}
</code></pre>

<p>I am getting java.lang.ClassCastException: com.sun.proxy.$Proxy36 cannot be cast to ItemReader on the Before and After. What am I missing? Is there anything else I need to setup for this (e.g. any annotations or entry in the config xml)? </p>
",https://stackoverflow.com/questions/43197700/itemreader-integration-testing-throwing-classcastexception,"['spring-boot', 'java-8', 'integration-testing', 'spring-batch']",755,TRUE,0,2
Integration Testing with Kitchen CI,"<p>I have cookbooks to deploy infrastructure to azure cloud. My cookbooks create required VMs, setup SQL Servers, attach disks to VM and some software installation.</p>

<p>I want that Kitchen CI itself:</p>

<ol>
<li>Verify that my resources have spawned correctly or not</li>
<li>Validate that configurations are done correctly or not</li>
</ol>
",https://stackoverflow.com/questions/46848539/integration-testing-with-kitchen-ci,"['continuous-integration', 'chef-infra', 'integration-testing', 'chef-solo', 'test-kitchen']",247,TRUE,0,1
Integration testing for image upload,"<p>I learned how to test image file uploading from this excellent article:
<a href=""https://jeffkreeftmeijer.com/2010/2014/using-test-fixtures-with-carrierwave/"" rel=""nofollow noreferrer"">https://jeffkreeftmeijer.com/2010/2014/using-test-fixtures-with-carrierwave/</a></p>

<p>Adapting those ideas for my app, I've got this test that works:</p>

<pre><code>test ""uploads an image"" do
    pic = Picture.create(:image =&gt; fixture_file_upload('/files/DJ.jpg','image/jpg'), :user =&gt; User.first) 
    assert(File.exists?(pic.reload.image.file.path))
end
</code></pre>

<p>I would like to test the same thing for the user interface, so I would think that this test would also pass:</p>

<pre><code>test ""create new picture"" do
    capybara_login(@teacher_1)
    click_on(""Upload Pictures"")
    fill_in ""picture_name"", with: ""Apple""
    attach_file('picture[image]', Rails.root + 'app/assets/images/apple.png')
    check(""check_#{@user_l.id}"")
    check(""check_#{@admin_l.id}"")
    click_on (""Create Picture"")

    @new_pic = Picture.last
    assert_equal ""Apple"", @new_pic.name
    assert @new_pic.labels.include?(@user_l)
    assert @new_pic.labels.include?(@admin_l)
    assert @teacher_1, @new_pic.user
    assert File.exists?(@new_pic.reload.image.file.path)
end
</code></pre>

<p>But it fails on the last line, asserting the existence of the file.</p>

<p>Below are the parts of my test_helper that I thought would be relevant. I can show the whole test_helper if someone thinks it necessary.</p>

<pre><code>ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require ""minitest/reporters""
require 'capybara/rails'
Minitest::Reporters.use!

CarrierWave.root = 'test/fixtures/files'

class CarrierWave::Mount::Mounter
  def store!
    # Not storing uploads in the tests
  end
end

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  include ApplicationHelper

  include ActionDispatch::TestProcess

  CarrierWave.root = Rails.root.join('test/fixtures/files')

  def after_teardown
    super
    CarrierWave.clean_cached_files!(0)
  end
end
</code></pre>

<p>Everything appears to be working as expected in development and production.</p>

<p>Thank you in advance for any insight.</p>
",https://stackoverflow.com/questions/45900127/integration-testing-for-image-upload,"['ruby-on-rails', 'capybara', 'carrierwave']",446,FALSE,0,0
Unit testing and Integration testing,"<p>i'm currently developping a nodejs/express rest api (personal project), and i wanted to learn as much as i ca from this project.</p>

<p>So in my project i'm using <code>sequelize</code> as an <code>ORM</code> layer, i have a model named `bus, and i have build CRUD endpoint to this model.</p>

<p>now i want to do some test this model/api i have developped, i read some tutorial about testing and found that there are multiple type of testing seperated in two big categories : white-box vs black-box.</p>

<p>So i have written some integration tests that test my api(integration test are black-box testing)</p>

<p>and i want right know to write some unit-testing, but i don't know what to test, the <code>bus</code> model is a Sequelize model, so everything that i would test would be already tested in the <code>sequelize</code> library it self. and testing the api endpoints is done via integration tests.</p>

<p>PS: its my first time writing tests.</p>

<p>i'm using the following technologies :  <code>nodejs</code>, <code>sequelize</code>, <code>express</code>, <code>mocha</code>, <code>chai</code>.</p>

<p><strong>Bus Model Definition</strong></p>

<pre><code>const Sequelize = require('sequelize');

module.exports = function(sequelize) {

    let Bus =  sequelize.define('bus', {
        name: {
            type: Sequelize.STRING,
        },
    });


    Bus.associate = function(models) {
        Bus.hasOne(models.LaneBus, {
            foreignKey: 'busId'
        });
    };

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

<p><strong>Bus Api endpoint testings</strong> </p>

<pre><code>const request = require('superagent');
const expect = require('chai').expect;

const app = require('../../src/app');
var http = require('http');

const models = require('../../src/models');


describe(""bus"", function () {

    var bus_id;

    it('should create bus', function (done) {

        request.post('http://localhost:3000/bus')
            .type('form')
            .send({
                name: 'bus_test_1',
            }).set('Accept', 'application/json')
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(201, 'invalid return code');
                expect(res.body.status).to.be.eq('success', 'invalid retun status');

                bus_id = res.body.id;

                done();
            })
    });

    it('should get list of bus', function (done) {

        request.get('http://localhost:3000/bus')
            .set('Accept', 'application/json')
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(200, 'invalid return code');
                expect(res.body.metadata).to.not.be.undefined

                done();
            })
    });


    it('should modify bus', function (done) {

        request.put(`http://localhost:3000/bus/${bus_id}`)
            .type('form')
            .send({
                name: 'bus_test_2'
            })
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(200, 'invalid return code');
                expect(res.body.status).to.be.eq('success', 'invalid retun status');
                done();
            });
    });

    it('modify bus should get error because bus dont exists', function (done) {

        request.put(`http://localhost:3000/bus/aaa`)
            .type('form')
            .send({
                name: 'bus_test_2'
            })
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(404, 'invalid return code');
                expect(res.body.status).to.be.eq('failure', 'invalid return code');
                done();
            });
    });


    it('should get bus', function (done) {

        request.get(`http://localhost:3000/bus/${bus_id}`)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(200, 'invalid return code');
                expect(res.body.name).to.be.eq('bus_test_2');
                done();
            });
    });

    it('get bus should return error because bus dont exist', function (done) {

        request.get(`http://localhost:3000/bus/aaaa`)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(404, 'invalid return code');
                expect(res.body.status).to.be.eq('failure', 'invalid return code');
                done();
            });
    });



    it('user role cannot create bus', function (done) {
        request.post('http://localhost:3000/bus')
            .type('form')
            .send({
                name: 'bus_test_1',
            }).set('Accept', 'application/json')
            .set('Authorization', global.JWT_TOKEN_TEST_USER)
            .end((err, res) =&gt; {
                expect(res.body.status).to.be.eq('failure', 'invalid retun status');


                done();
            })
    })

    it('user role cannot modify bus', function (done) {
        request.put(`http://localhost:3000/bus/${bus_id}`)
            .type('form')
            .send({
                name: 'bus_test_2'
            })
            .set('Authorization', global.JWT_TOKEN_TEST_USER)
            .end((err, res) =&gt; {
                expect(res.body.status).to.be.eq('failure', 'invalid retun status');
                done();
            });
    })


    it('user role cannot delete bus', function (done) {
        request.delete(`http://localhost:3000/bus/${bus_id}`)
            .set('Authorization', global.JWT_TOKEN_TEST_USER)
            .end((err, res) =&gt; {
                expect(res.body.status).to.be.eq('failure', 'invalid return code');
                done();
            });
    })


    it('should delete bus', function (done) {

        request.delete(`http://localhost:3000/bus/${bus_id}`)
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(200, 'invalid return code');
                done();
            });
    });

    it('delete bus should get error because bus dont exist', function (done) {

        request.delete(`http://localhost:3000/bus/${bus_id}`)
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(404, 'invalid return code');
                expect(res.body.status).to.be.eq('failure', 'invalid return code');
                done();
            });
    });





});
</code></pre>
",https://stackoverflow.com/questions/44724136/unit-testing-and-integration-testing,"['node.js', 'unit-testing', 'express', 'testing', 'mocha.js']",602,TRUE,-1,2
Integration testing and spring application events,"<p>I have a spring rest controller which fires a ApplicationEvent </p>

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

@Autowired
private VehicleService service;

@Autowired
private ApplicationEventPublisher eventPublisher;

@RequestMapping(value = ""/public/rest/vehicle/add"", method = RequestMethod.POST)
public void addVehicle(@RequestBody @Valid Vehicle vehicle){
    service.add(vehicle);
    eventPublisher.publishEvent(new VehicleAddedEvent(vehicle));
    }
}
</code></pre>

<p>And I have a integration test for the controller, something like</p>

<pre><code>    @RunWith(SpringRunner.class)
    @WebMvcTest(controllers = VehicleController.class,includeFilters = @ComponentScan.Filter(classes = EnableWebSecurity.class))
    @Import(WebSecurityConfig.class)

public class VehicleControllerTest {
@Autowired
private MockMvc mockMvc;

@MockBean
private VehicleService vehicleService;

@Test
public void addVehicle() throws Exception {
    Vehicle vehicle=new Vehicle();
    vehicle.setMake(""ABC"");
    ObjectMapper mapper=new ObjectMapper();
    String s = mapper.writeValueAsString(vehicle);

    given(vehicleService.add(vehicle)).willReturn(1);

    mockMvc.perform(post(""/public/rest/vehicle/add"").contentType(
            MediaType.APPLICATION_JSON).content(s))
            .andExpect(status().isOk());
   }
}
</code></pre>

<p>Now, if I remove the event publishing line, the test successes. However, with the event, it hits error.</p>

<pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: null source
</code></pre>

<p>I tried bunch of different things, to avoid or skip the line in testing but nothing helped. Could you please tell me what is the right way to test such code? Thanks in advance </p>
",https://stackoverflow.com/questions/45128648/integration-testing-and-spring-application-events,"['spring', 'junit', 'mockito', 'integration-testing']",3273,TRUE,7,1
iOS UI Testing vs Integration Testing,"<p>So I've been trying to read about UI and Integration testing (specifically for iOS development). I always though these tests were different, but a lot of the integration tests example I see, appear to be what I would call UI testing. </p>

<p>So now I'm curious, what is the difference between UI and integration testing? Could you please give examples?</p>
",https://stackoverflow.com/questions/46625010/ios-ui-testing-vs-integration-testing,"['ios', 'xcode', 'unit-testing', 'integration-testing', 'ui-testing']",5304,TRUE,7,1
Integration testing of JAX-RS services,"<p>I recently implemented simple JAX-RS REST endpoint. I'm wondering is there any transparent way of integration testing?</p>

<p>I searched a bit on stackowerflow and found these questions: <a href=""https://stackoverflow.com/questions/121266/unit-testing-a-jax-rs-web-service"">first</a>, <a href=""https://stackoverflow.com/questions/8878190/running-unit-tests-on-the-server-jax-rs"">second</a>. They are a bit outdated and I hope there is already some better way of testing. The solutions proposed there don't solve my problem as they provide either vendor-specific or some complex third party ways. </p>

<p><strong>Q:</strong> What is the modern way of testing JAX-RS services? Does Java EE provide solution for that? Or generally what is the best way of writing controller tests in Java EE ecosystem?</p>

<p>To be more specific I'm looking for some way that allows to easily test a REST call. In spring framework it usually looks like this:</p>

<pre><code>@Autowired
MockMvc mvc;
@MockBean
MyService service;

@Test
public void shouldGetMyDto() {
    MyDto dto = new MyDto(""test-id"", ""test-name"");
    given(service.getMyDto(""test-id"")).willReturn(dto);

    mvc.perform(get(""/api/my-entities/test-id""))
            .andExpect(status().isOk())
            .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath(""$.id"", is(""test-id"")))
            .andExpect(jsonPath(""$.name"", is(""test-name"")));

    verify(service).getMyDto(""test-id"");
}
</code></pre>
",https://stackoverflow.com/questions/47459943/integration-testing-of-jax-rs-services,"['java', 'rest', 'jakarta-ee', 'junit', 'jax-rs']",5377,TRUE,6,1
Spring Boot Integration Testing with mocked Services/Components,"<p><strong>Situation and Problem</strong>: In Spring Boot, how can I inject one or more mocked classes/beans into the application to do an integration test? There are a few answers on StackOverflow, but they are focused on the situation before Spring Boot 1.4 or are just not working for me.</p>

<p>The background is, that in the code bellow the implementation of Settings relies on third party servers and other external systems. The functionality of Settings is already tested in a unit test, so for a full integration test I want to mock out the dependency to these servers or system and just provide dummy values.</p>

<p>MockBean will ignore all existing bean definitions and provide a dummy object, but this object doesn't provide a method behavior in other classes that inject this class. Using the @Before way to set the behavior before a test doesn't influence the injected object or isn't injected in other application services like AuthenticationService.</p>

<p><strong>My question</strong>: How can I inject my beans into the application context? 
My test:</p>

<pre><code>package ch.swaechter.testapp;

import ch.swaechter.testapp.utils.settings.Settings;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.junit4.SpringRunner;

@TestConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyApplication.class})
public class MyApplicationTests {

    @MockBean
    private Settings settings;

    @Before
    public void before() {
        Mockito.when(settings.getApplicationSecret()).thenReturn(""Application Secret"");
    }

    @Test
    public void contextLoads() {
        String applicationsecret = settings.getApplicationSecret();
        System.out.println(""Application secret: "" + applicationsecret);
    }
}
</code></pre>

<p>And bellow a service that should use the mocked class, but doesn't receive this mocked class:</p>

<pre><code>package ch.swaechter.testapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    private final Settings settings;

    @Autowired
    public AuthenticationServiceImpl(Settings settings) {
        this.settings = settings;
    }

    @Override
    public boolean loginUser(String token) {
        // Use the application secret to check the token signature
        // But here settings.getApplicationSecret() will return null (Instead of Application Secret as specified in the mock)!
        return false;
    }
}
</code></pre>
",https://stackoverflow.com/questions/42641853/spring-boot-integration-testing-with-mocked-services-components,"['java', 'spring-boot', 'junit4', 'spring-test']",25446,TRUE,20,2
ASP.NET Core running two TestServer for Integration Testing,"<p>I am trying to run some integration tests for a token management API.  The API also requires the token issuer API to be running.</p>

<p>In summary, my integration test needs to run both IdentityServer4 Web/API and the Management API simultaneously.  When I create two instances of <code>TestServer</code>, it seems like they both end up with the same <code>BaseAddress</code> (<code>http://localhost</code>).</p>

<pre><code>private readonly TestServer _identityTestServer;
private readonly TestServer _mgmtTestServer;
private readonly AppMgmtConfig _config;
private readonly AdminClient _adminClient;
private const string _certificatePassword = ""test"";

public AdminClientTests() : base(nameof(AdminClientTests))
{
    var connectionString = GetConnectionString();
    var dbSettings = new DbSettings(connectionString);

    Environment.SetEnvironmentVariable(""IdentityServer4ConnString"",
        dbSettings.IdentityServerConnectionString);
    Environment.SetEnvironmentVariable(""CertificatePassword"", _certificatePassword);

    _identityTestServer = new TestServer(new WebHostBuilder()
        .UseStartup&lt;USBIdentityServer.Startup&gt;()
        .UseEnvironment(""IntegrationTest""));
    USBIdentityServer.Program.InitializeDatabase(_identityTestServer.Host);

    _mgmtTestServer = new TestServer(new WebHostBuilder()
        .UseStartup&lt;IdentityServer4.Management.Startup&gt;()
        .UseEnvironment(""IntegrationTest""));

    _config = GetConfig();
    _adminClient = new AdminClient(_config);
}
</code></pre>

<p><strong>NOTE:</strong>
Things I have already tried:</p>

<ul>
<li>Add <code>.UseUrls(""http://localhost:5001"")</code> to see if TestServer will run on that port.</li>
<li>Add <code>serverName.BaseAddress = new Uri(""http://localhost:5001"");</code> to see if TestServer will run on that port.</li>
</ul>

<p>Neither of these seems to impact it.</p>
",https://stackoverflow.com/questions/47081905/asp-net-core-running-two-testserver-for-integration-testing,"['c#', 'asp.net-core', 'integration-testing']",8279,TRUE,19,4
Gitlab continuous integration testing with Selenium,"<p>I am working on a project to build, test and deploy an application to the cloud using a <strong>.gitlab-ci.yml</strong></p>

<p><strong>1) Build the backend and frontend using pip install and npm install</strong></p>

<pre><code>build_backend:
  image: python
  stage: build
  script:
  - pip install requirements.txt
  artifacts:
    paths:
      - backend/

build_frontend:
  image: node
  stage: build
  script:
  - npm install
  - npm run build
  artifacts:
    paths:
      - frontend
</code></pre>

<p><strong>2) Run unit and functional tests using PyUnit and Python Selenium</strong></p>

<pre><code>test_unit:
  image: python
  stage: test
  script:
    - python -m unittest discover

test_functional:
  image: python
  stage: test
  services:
    - selenium/standalone-chrome
  script:
    - python tests/example.py http://selenium__standalone-chrome:4444/wd/hub https://$CI_BUILD_REF_SLUG-dot-$GAE_PROJECT.appspot.com
</code></pre>

<p><strong>3) Deploy to Google Cloud using the sdk</strong></p>

<pre><code>deploy:
  image: google/cloud-sdk
  stage: deploy
  environment:
    name: $CI_BUILD_REF_NAME
    url: https://$CI_BUILD_REF_SLUG-dot-$GAE_PROJECT.appspot.com
  script:
    - echo $GAE_KEY &gt; /tmp/gae_key.json
    - gcloud config set project $GAE_PROJECT
    - gcloud auth activate-service-account --key-file /tmp/gae_key.json
    - gcloud --quiet app deploy --version $CI_BUILD_REF_SLUG --no-promote
  after_script:
    - rm /tmp/gae_key.json
</code></pre>

<p>This all runs perfectly, except for the selenium tests are run on the deployed url not the current build:</p>

<pre><code>python tests/example.py http://selenium__standalone-chrome:4444/wd/hub https://$CI_BUILD_REF_SLUG-dot-$GAE_PROJECT.appspot.com
</code></pre>

<p>I need to have gitlab run three things simultaneously:
 a) Selenium
 b) Python server with the application
 - Test script</p>

<p>Possible approaches to run the python server:</p>

<ul>
<li>Run within the same terminal commands as the test script somehow</li>
<li>Docker in Docker</li>
<li>Service</li>
</ul>

<p>Any advice, or answers would be greatly appreciated!</p>
",https://stackoverflow.com/questions/44206382/gitlab-continuous-integration-testing-with-selenium,"['selenium', 'continuous-integration', 'gitlab', 'gitlab-ci', 'gitlab-ci-runner']",5913,FALSE,4,1
integration testing api having fluent validation,"<p>I have API which uses FluentValidations.</p>

<p>I am writing integration test and wanted to assert that bad request response contains error field name and messages.  I want to check for fieldname, and message and ensure they are same as returned from fluentvalidations.   Am getting a json response filled with validation errors but not sure into which object should i deserialize into.</p>

<pre><code>response.StatusCode.Should().Be(HttpStatusCode.BadRequest);

var result = JsonConvert.DeserializeObject&lt;?&gt;(await response.Content.ReadAsStringAsync());
result.Should().BeOfType&lt;?&gt;();
result.Should().NotBeNull();
result.Should().HaveCount(something);
</code></pre>

<p>sample response is fluentvalidation response</p>

<pre><code>{
  ""Name"": [
    ""Name is required."",
    ""Name length cannot be more that 255 chars""
  ],
  ""ListTypeId"": [
    ""Invalid listtypeid""
  ],
  ""PartyRoleId"": [
    ""Invalid partyroleid""
  ]
}
</code></pre>
",https://stackoverflow.com/questions/43943149/integration-testing-api-having-fluent-validation,"['c#', 'asp.net-web-api2', 'fluentvalidation']",616,TRUE,4,1
Details on Umbrella approach Integration Testing,"<p>I have been researching on the Umbrella Integration testing approach and most of the sites I can across seem to have the exact same definition for it:</p>

<blockquote>
  <p>The umbrella approach requires testing along functional data and control-flow paths. First, the inputs for functions are integrated in the bottom-up pattern discussed above. The outputs for each function are then integrated in the top-down manner. The primary advantage of this approach is the degree of support for early release of limited functionality. It also helps minimize the need for stubs and drivers. The potential weaknesses of this approach are significant, however, in that it can be less systematic than the other two approaches, leading to the need for more regression testing.</p>
</blockquote>

<p>However, this seems vague and I would like to have a better description as well as some advantages and disadvantages.</p>

<p>Some of the websites I came across:</p>

<p><a href=""http://www.technofunc.com/index.php/erp/178-what-is-integration-testing"" rel=""nofollow noreferrer"">http://www.technofunc.com/index.php/erp/178-what-is-integration-testing</a>
<a href=""https://msdn.microsoft.com/en-us/library/aa292128(v=vs.71).aspx"" rel=""nofollow noreferrer"">https://msdn.microsoft.com/en-us/library/aa292128(v=vs.71).aspx</a></p>
",https://stackoverflow.com/questions/43488076/details-on-umbrella-approach-integration-testing,"['testing', 'integration-testing']",283,FALSE,3,0
Integration testing Azure Service Bus with Docker,"<p>What is an appropriate way to integration test systems that use ASB?  With something like Kafka and using docker-compose, I could spin up two services that will communicate asynchronously over Kafka.  Is there a way to do something similar with ASB?  If not, what is a common integration testing pattern?</p>
",https://stackoverflow.com/questions/46007682/integration-testing-azure-service-bus-with-docker,"['azure', 'docker-compose', 'integration-testing', 'azureservicebus']",9172,TRUE,9,3
OWIN Integration testing - HttpContext is null,"<p>I have OWIN Web API app that I am trying to integration test. In order to do this I am creating a server in memory like so:</p>

<pre><code>    private TestServer _server;

    [TestInitialize]
    public void Intitialize()
    {
        _server = TestServer.Create&lt;Startup&gt;();
    }
</code></pre>

<p>Integration test:</p>

<pre><code>  [TestMethod]
  public async Task Test_Controller()
  {
      //Act
      var response = await _server.HttpClient.GetAsync(""/controller/test"");

      //Assert
      Assert.AreEqual(HttpStatusCode.Ok, response.StatusCode);
   }
</code></pre>

<p>In my controller I am trying to access some information from the HttpContext, unfortunately, this is always null during the integration test and therefore it throws an exception. </p>

<p>Is there anyway I can mock the the httpcontext during my integration tests? </p>
",https://stackoverflow.com/questions/45907810/owin-integration-testing-httpcontext-is-null,"['c#', 'asp.net-web-api', 'integration-testing', 'owin']",1189,TRUE,2,1
WebAPI - routes (integration) testing - 404 error,"<p>I'm trying to make a first integration test of my Web Api project. The target get action is available for anonymous users, but I get the 404 error in the test:</p>

<pre><code>string url = ""http://localhost:28000"";

var config = new HttpConfiguration();

config.Routes.MapHttpRoute(""DefaultApi"", ""api/{controller}/{id}"", new { routetemplate = ""Version"", id = RouteParameter.Optional });
config.Routes.MapHttpRoute(name: ""ApiWithActionName"", routeTemplate: ""api/{controller}/{action}/{id}"", defaults: new { id = RouteParameter.Optional });

using (var server = new HttpServer(config))
{
   using (var client = new HttpClient(server))
   {
       var response = client.GetAsync($""{url}/api/values"").Result;

       Assert.IsTrue(response.StatusCode == System.Net.HttpStatusCode.OK);

       var answer = response.Content.ReadAsStringAsync().Result;

       Assert.IsTrue(answer.Contains(""ok""));
   }
}
</code></pre>
",https://stackoverflow.com/questions/46099696/webapi-routes-integration-testing-404-error,"['c#', 'unit-testing', 'asp.net-web-api2', 'integration-testing']",667,TRUE,2,1
Spring integration: testing poller dependent logic,"<p>I wonder how could I write spring tests to assert logic chain which is triggered by 'SourcePollingChannelAdapter'. </p>

<p>What comes to my mind:</p>

<ul>
<li>use Thread.sleep() which is really bad idea for tests</li>
<li>Have another test version of spring context where I will replace all pollable channels with direct ones. This requires much work.</li>
</ul>

<p>Are there any common ways to force trigger poller within test?</p>
",https://stackoverflow.com/questions/47833131/spring-integration-testing-poller-dependent-logic,"['spring', 'testing', 'spring-integration']",441,TRUE,2,1
Ember integration testing and keyboard shortcuts,"<p>I'm having issues testing the following behavior with an integration test:</p>

<blockquote>
  <p>When a checkbox is focused, and I press the space bar, the checkbox gets checked.</p>
</blockquote>

<p>If I override the keyDown event in my component I can catch the event, but it doesn't seem to fall down to the normal behavior and doesn't check the checkbox.
However, when I manually test it, it works like a charm.</p>

<p>For the event, I'm using this:</p>

<p><code>this.$(':checkbox:eq(0)').trigger(jQuery.Event( 'keydown', { keyCode: 32 } ))</code></p>

<p>Thank you very much for your help!</p>
",https://stackoverflow.com/questions/42211018/ember-integration-testing-and-keyboard-shortcuts,"['ember.js', 'qunit']",114,FALSE,1,0
Ruby on rails - Devise - Integration Testing,"<p>I am trying to test my sign up page but I don't understand why it doesn't work. </p>

<pre><code>   #SIGN UP FLOWS
    test ""signed up user with valid info is redirected to root"" do
     get root_path

     post user_registration_path, :user_email =&gt; ""asasas@as.com"", :user_password =&gt;  ""asasas"", :user_password_confirmation =&gt;  ""asasas""
     follow_redirect!
     assert_equal ""/"", path
    end
</code></pre>

<p>I have also tried :</p>

<pre><code>   #SIGN UP FLOWS
    test ""signed up user with valid info is redirected to posts"" do
     get root_path
     @david = User.create(email: ""aaaasadasadaddamdaaa@aaa.com"", password: Devise::Encryptor.digest(User, ""aaaaaa""))
     post user_registration_path, 'user[email]' =&gt; @david.email, 'user[password]' =&gt;  @david.password, 'user[password_confirmation]' =&gt;  @david.password

     assert_equal ""/"", path
   end
</code></pre>

<p>Instead of going to my root which is <code>/</code> It stays on the same page. I tried to do <code>follow_redirect!</code> but it gives me the error that reduction is not possible because <code>RuntimeError: not a redirect! 200 OK</code>. </p>

<p>What am I doing wrong? I have looked at devise GitHub page but there is no information about registration testing. </p>
",https://stackoverflow.com/questions/47770902/ruby-on-rails-devise-integration-testing,"['ruby-on-rails', 'ruby', 'authentication', 'post', 'devise']",53,FALSE,1,0
Unit or Integration testing for SSH?,"<p>I am currently using <a href=""https://github.com/phpseclib/phpseclib"" rel=""nofollow noreferrer"">phpseclib</a> to allow me to connect to SSH.</p>

<p>I will be using phpseclib quite a lot to connect to many servers via SSH and execute some commands. </p>

<p>I have created a <code>SecureShell</code> class (like a adaptor pattern) with a few methods such as <code>login()</code> and <code>exec()</code>. These method will execute the server via phpseclib object.</p>

<p>I am trying to work out what is a good way to test the login and execute a command a server - should I mock it <code>SecureShell</code> class or do  Integration testing which mean I need a separate real testing server (not development local server?)</p>
",https://stackoverflow.com/questions/46393657/unit-or-integration-testing-for-ssh,"['php', 'unit-testing', 'phpunit', 'phpseclib']",1152,TRUE,1,1
Integration testing in ASP.NET Core Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationFailedException,"<p>For this error, I have tried multiple solutions which is provided by Github. But, none of them worked. Please help to check whether this issue reopen on new environment like below.
Environment:
VS 2017 Version 15.4.1
Dotnet Version 2.0.2</p>

<p>Reproduce Steps:</p>

<ol>
<li>Create an Asp.Net Core Web Application->.NET Core and Asp.net Core 2.0-> Web Application(Model-View-Controller)</li>
<li>Create an xUnit Test Project(.NET Core) </li>
<li>Follow this link <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""nofollow noreferrer"">Integration testing in ASP.NET Core</a></li>
<li>Add true to Test.csproj which is pointed at above link.</li>
<li>Run test method will return below error.</li>
</ol>

<blockquote>
  <p>Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationFailedException : One or more compilation failures occurred:
  ewiqttdv.z4g(4,62): error CS0012: The type 'Attribute' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.</p>
</blockquote>

<p>Update: 
After following <a href=""https://github.com/aspnet/Hosting/issues/959#issuecomment-286351703"" rel=""nofollow noreferrer"">this suggestion</a> , this error gone, but, it produce below new error.</p>

<blockquote>
  <p>Message: System.IO.FileNotFoundException : Could not load file or assembly 'Microsoft.VisualStudio.Web.CodeGeneration, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.</p>
</blockquote>

<p>What is the possible way to resolve ""Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationFailedException""?</p>

<p>Any help would be appreciated.</p>
",https://stackoverflow.com/questions/47007185/integration-testing-in-asp-net-core-microsoft-aspnetcore-mvc-razor-compilation-c,"['asp.net-core-mvc', 'integration-testing', 'asp.net-core-2.0', 'razor-2']",439,TRUE,1,1
Post Deployment Integration Testing in Mule,"<p>I have an application for which I have an Integration Test suite written using Munit. I am deploying this to CloudHub Using Jenkins. </p>

<p>How can I execute the test cases post-deployment?</p>

<p>Is there any command line tool that can  I make use of or it can done using maven or Jenkins?</p>
",https://stackoverflow.com/questions/47015489/post-deployment-integration-testing-in-mule,"['maven', 'testing', 'mule', 'integration', 'munit']",786,TRUE,0,1
Java/Groovy integration testing protected resources,"<p>I want to write integration tests for my application which is using JWT authentication.</p>

<pre><code>@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, ""/login"").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new MyJWTLoginFilter(""/login"", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new MyJWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
</code></pre>

<p>My groovy test:</p>

<pre><code> @ContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Stepwise
class MyControllerSpec extends Specification {

    @Autowired
    private TestRestTemplate testRestTemplate

def 'findAll() test'() {
        when:
            def result = testRestTemplate.getForEntity('/findAll', User[])

        then:
            result.getStatusCode() == HttpStatus.OK
            result.getBody().toList().size() == 1
    }
</code></pre>

<p>But I need to place a token in header. How can do that?</p>
",https://stackoverflow.com/questions/45098510/java-groovy-integration-testing-protected-resources,"['java', 'spring', 'groovy', 'spring-security', 'integration-testing']",130,FALSE,0,1
Docker compose and concurrent integration testing,"<p><strong>Edit:</strong> sorry, I was mistaken about the first part of this question.</p>

<p><s>So I have a <code>docker-compose.yaml</code> that's working fine when ran synchronously:</p>

<pre><code>server:
  build: .
  dockerfile: ""./docker/integration_tests/server/Dockerfile""
  links:
    - mongo
  environment:
    - ""MONGO_URI=mongodb://mongo:27017/company""

mongo:
  image: 'mongo:3.2.6'
  ports:
    - ""27017""
</code></pre>

<p>When launched with this command: <code>docker-compose build &amp;&amp; docker-compose up --abort-on-container-exit</code></p>

<p>However when I launch two or three jobs to test if it works in parallel (this is in Jenkins using pipelines, so they have different directories) I'm seeing this on job A:</p>

<pre><code>Successfully built 7b23b3a7b823
+ docker-compose up --abort-on-container-exit
Creating companyservercicd3_mongo_1

ERROR: for mongo  Cannot start service mongo: driver failed programming external connectivity on endpoint companyservercicd3_mongo_1 (422826f73ce76526e4072f72a2b44467f9080e79a24d37d1fe2bba903854a698): Bind for 0.0.0.0:27017 failed: port is already allocated
Encountered errors while bringing up the project.
</code></pre>

<p>And this on job B:</p>

<pre><code>Successfully built 80aa795867eb
+ docker-compose up --abort-on-container-exit
Creating companyservercicd4_mongo_1

ERROR: for mongo  Cannot start service mongo: driver failed programming external connectivity on endpoint companyservercicd4_mongo_1 (1591f2847e6c0d81f2c530874201ea912fa59ea35bfa27e5b25d7843e06da6b5): Bind for 0.0.0.0:27017 failed: port is already allocated
Encountered errors while bringing up the project.
</code></pre>

<p>The docs say this about the <code>ports</code> config option:</p>

<blockquote>
  <p>Expose ports. Either specify both ports (HOST:CONTAINER), or just the
  container port (a random host port will be chosen).</p>
</blockquote>

<p>I must be misunderstanding something because I thought <code>27017</code> would be within a container, and that each job would have its own container. What am I doing wrong here?</s></p>

<p>Another somewhat related question - this works well in Jenkins because Jenkins is creating a new directory per job so there are no name conflicts, but would there be a way to make this bulletproof by passing in an option that would let each run have its own name? Another user recommended doing this as a workaround: </p>

<pre><code>`docker-compose run --rm --no-deps --name `uuidgen` ...`
</code></pre>

<p>But that would require me to rework my docker-compose.yml and convert the <code>up</code> command into the equivalent <code>build/create/start/attach</code></p>
",https://stackoverflow.com/questions/42589685/docker-compose-and-concurrent-integration-testing,"['docker', 'jenkins', 'concurrency', 'parallel-processing', 'docker-compose']",775,FALSE,0,1
Spring transfer SecurityContext for Integration testing,"<p>i want to test my REST Endpoints. In my REST methods are some filters based on the SecurityContext. When i set the SecurityContext in my test classes and call the rest methods, the SecurityContext is deleted. Only when i create the SecurityContext in my REST methods it has an effect. 
Is there a possibility how to transfer the context?</p>

<pre><code>SecurityContext securityContext = new SecurityContextImpl();
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
    // is here User ...
    .mockMvc.perform(get(""/test""...)
</code></pre>

<p>RestController:</p>

<pre><code>public ResponseEntity&lt;...&gt; getTest(){
 // is now anonymus
 SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
</code></pre>

<p>thank you</p>
",https://stackoverflow.com/questions/41873659/spring-transfer-securitycontext-for-integration-testing,"['java', 'spring', 'rest', 'spring-security']",948,FALSE,0,1
Unsatisfied dependencies with Weld during integration testing,"<p>I am able to deploy a RESTEasy application working well with Weld (meaning my CDI works) but I am having some trouble with my integration tests. I get this error:</p>

<pre><code>org.jboss.weld.exceptions.DeploymentException:
WELD-001408: Unsatisfied dependencies for type SomeService with qualifiers @Default
</code></pre>

<p>while testing:</p>

<pre><code>@RunWith(WeldJUnit4Runner.class)
public class SomeServiceIT {

    @Inject
    private SomeService service;

    @Test
    public void test() {
        System.out.println(service);
    }
}
</code></pre>

<p>The last message in my logs is</p>

<pre><code>DEBUG::WELD-000100: Weld initialized. Validating beans
</code></pre>

<p>Content of src/test/resources/META-INF/beans.xml:</p>

<pre><code>&lt;beans xmlns=""http://xmlns.jcp.org/xml/ns/javaee""
    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd""
    version=""1.1"" bean-discovery-mode=""all""&gt;
&lt;/beans&gt;
</code></pre>

<p>By the way I tried the <code>cdi-unit</code> library and it works, but I need to use my own <code>WeldJUnit4Runner</code> which is currently:</p>

<pre><code>public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {

    private final Weld weld;
    private final WeldContainer container;

    public WeldJUnit4Runner(Class&lt;?&gt; klass) throws InitializationError {
        super(klass);
        this.weld = new Weld();
        this.container = weld.initialize();
    }

    @Override
    protected Object createTest() throws Exception {
        return container.instance().select(getTestClass().getJavaClass()).get();
    }
}
</code></pre>

<p>I use <code>weld-se</code> 2.4.1.Final for testing.<br>
Thanks.</p>

<p>EDIT:<br>
So it seems like Weld only looks into src/test/java (when I copy SomeService over to src/test/java it woks). This is silly, I am not going to duplicate all my classes to test them... How to tell Weld to retrieve classes from src/main/java?</p>
",https://stackoverflow.com/questions/41836690/unsatisfied-dependencies-with-weld-during-integration-testing,"['testing', 'integration-testing', 'cdi', 'weld', 'jboss-weld']",1667,TRUE,7,3
Create URLs dedicated to integration testing,"<p>Trying to test a simple feature which is contained in a  very complex feature.</p>

<p>The simple feature requires multiple steps before it can be launched. These steps have many consequences on the database, but they don't have any interaction with the feature itself.</p>

<p>Since we'd like to test this simple feature only through our API, one of the idea was to create a route dedicated to testing this. We'd then do a cron visiting that route once in a while, testing whether or not the feature still works.</p>

<p>I find it kinda disturbing to have one or many route(s) existing only for the sole purpose of testing. But I can see the advantages which are numerous.</p>

<p>Is that good practice or is there a better way to do it ?</p>
",https://stackoverflow.com/questions/47197295/create-urls-dedicated-to-integration-testing,"['php', 'laravel', 'testing', 'lumen', 'web-api-testing']",46,TRUE,0,1
OSB INTEGRATION TESTING THROUGH SOAP UI,"<p>I want do OSB Integration Testing. Like i am putting up some data on OSB and then validating the data i have put on OSB. Is it possible to do testing through SOAP UI. If yes, then how, what are the steps to do it. 
Any one who has worked on it, or has some information kindly help.</p>
",https://stackoverflow.com/questions/43386032/osb-integration-testing-through-soap-ui,"['soapui', 'osb']",336,TRUE,-3,2
Integration Testing with .NET Core and NUnit,"<p>I have a controller that is taking a JWT Claim, and if the claim is correct, then I am returing a Json string of categories as follows :-</p>

<pre><code>[Authorize(Policy = ""OnlyValidUsers"")]
[Route(""api/[controller]"")]
public class CategoriesController : Controller
{
    private readonly IGenericService&lt;Category&gt; _categoriesService;

    public CategoriesController(IGenericService&lt;Category&gt; categoriesService)
    {
        _categoriesService = categoriesService;
    }

    [Authorize(Policy = ""GenericUser"")]
    [HttpGet(""/api/Categories/Get"", Name = ""GetCategories"")]
    public async Task&lt;IActionResult&gt; Get()
    {
        var categories = await _categoriesService.GetAll();
        return Json(categories);
    }
}
</code></pre>

<p>This happens after the user logins in to my system, and gets a bearer token.</p>

<p>I am trying to test that in an integration test as follows:-</p>

<pre><code>[TestFixture]
public class CategoriesControllerIntegrationTests
{
    private HttpClient _client;
    private Category _testCategory;
    private string _request;

    [SetUp]
    public void Setup()
    {
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var projectPath = Path.GetFullPath(Path.Combine(basePath, ""../../../../SportsStore.Tests""));

        var server = new TestServer(Utils.GetHostBuilder(new string[] { })
            .UseContentRoot(projectPath)
            .UseEnvironment(""Development"")
            .UseStartup&lt;Startup&gt;());

        _client = server.CreateClient();
        _testCategory = new Category
        {
            Name = Enums.GetEnumDescription(Enums.CategoryTestData.Name)
        };
        _request = Enums.GetEnumDescription(Enums.Requests.Categories);
    }

    [Test]
    public async Task Get_ReturnsAListOfCategories_CategoriesController()
    {
        var response = await _client.GetAsync(_request + ""Get"");
        response.EnsureSuccessStatusCode();

        Assert.IsTrue(true);
    }
</code></pre>

<p>The Utils class is as follows:-</p>

<pre><code>public class Utils
{
    public static IWebHostBuilder GetHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
                   .AddCommandLine(args)
                   .AddEnvironmentVariables(prefix: ""ASPNETCORE_"")
                   .Build();

        return new WebHostBuilder()
            .UseConfiguration(config)
            .UseKestrel()
            .UseStartup&lt;Startup&gt;();
    }
}
</code></pre>

<p>When I run the test, I am getting a 401 (Unauthorized) which is expected.  How can I make this test pass?  How can I pass the claim in the test to verify that its working?</p>

<p>Also, if I remove the [Authorize] filters, I am still getting a 401 (Unauthorized) which I think should not happen.</p>

<p>Any help will be greatly appreciated!</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/43367389/integration-testing-with-net-core-and-nunit,"['testing', 'asp.net-core', 'nunit', 'integration-testing', '.net-core']",2866,TRUE,4,1
How to implement integration testing for IdentityServer4?,"<p>This is more of a general question not a specific one, but I hope it might help someone in the future with the similar problem.</p>

<p>I am implementing IdentityServer4 for my business case where I initially want to set up authentication and authorization for a public API access. For that I will be initially using only ClientCredentials flow. For manually testing the usage flow and correct configuration and setup, I have created a small test API and a Client console app as in the sample projects from the documentation. But I want to automate it as I have almost completed the IdentityServer4 setup and am going to start working on the actual API itself.</p>

<p>So basically I want to do some integration testing against my implementation of the IdentityServer. But I have minimal experience regarding this topic so maybe you would have some suggestions or tips on how to set it up.</p>

<p>Should I set it up on the API side, when at least some endpoints are already done? But if my IdentityServer and the API are in different solutions, then for example for running these tests locally, I would still have to start IdentityServer manually and then could run the tests on the API project which connect against it?</p>

<p>Or for me it would make more sense to have the tests, the test api and client in the IdentityServer project (much in the same way it is done in the source code solution). But when looking at the source code integration tests, I saw they had a separate Startup class for IdentityServer startup. Should I do this similarly or rather configure the tests to run against the Startup class of my own IdentityServer project? Then I would have to copy all the appSettings files etc.</p>

<p>I know it's quite a general question and topic, but any pointers will be appreciated on how to actually test the correct thing. I know I don't need to test a lot about the functionality itself as it's also done in the source code solution, but I would rather have the integration tests for testing my own configuration etc, so if any of the components fail to communicate to each other, I would know immediately.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/47473421/how-to-implement-integration-testing-for-identityserver4,"['testing', 'asp.net-core', 'integration-testing', 'identityserver4', 'asp.net-core-2.0']",2227,TRUE,3,1
Integration testing for a Spark Streaming application,"<p>I am trying to write the integration test for a complex spark streaming application, which has different input and output support.
After starting the application, a REST call is made which submits the json containing various Config params and component info. 
while I am trying to write the test case for socket as input and console as output I am pretty much confused as in how do I test the application as whole i.e submit the streaming data from the socket and then comparing the output from the console.</p>

<p>The application produces the output on the console itself via dataframe.println 
what is the approach to do the Integration testing?</p>
",https://stackoverflow.com/questions/45781561/integration-testing-for-a-spark-streaming-application,"['sockets', 'apache-spark', 'integration-testing', 'spark-streaming', 'scalatest']",248,FALSE,1,0
InMemory DbContext throws error when integration testing,"<p>Error:</p>

<blockquote>
  <p>Message: System.InvalidOperationException : The instance of entity
  type 'Program' cannot be tracked because another instance of this type
  with the same key is already being tracked. When adding new entities,
  for most key types a unique temporary key value will be created if no
  key is set (i.e. if the key property is assigned the default value for
  its type). If you are explicitly setting key values for new entities,
  ensure they do not collide with existing entities or temporary values
  generated for other new entities. When attaching existing entities,
  ensure that only one entity instance with a given key value is
  attached to the context.</p>
</blockquote>

<p>Integration test:</p>

<pre><code>public class ProgramControllerIntegrationTests : MappingTestsHelper
    {
        private readonly IMapper _mapper;
        private readonly Repository&lt;ApplicationDbContext&gt; _repository;
        private ProgramService _programService;
        private readonly ProgramController _classUnderTest;
        private readonly ValidatorService _validatorService;
        private readonly FluentValidatorFactory _fluentValidatorFactory;
        private readonly ClaimsService _claimsService;

        public ProgramControllerIntegrationTests()
        {
            var container = new Container();
            container.Configure(c =&gt; {
                c.AddRegistry&lt;DependencyInjectionRegistry&gt;();
                c.For&lt;AbstractValidator&lt;CreateViewModel&gt;&gt;().Use&lt;CreateViewModelValidator&gt;();
            });

            _mapper = Mapper.Instance;
            _repository = new Repository&lt;ApplicationDbContext&gt;(GetContextWithData());
            _programService = new ProgramService(_repository, _mapper);
            _fluentValidatorFactory = new FluentValidatorFactory(container);
            _validatorService = new ValidatorService(_fluentValidatorFactory);
            _claimsService = new ClaimsService();
            _classUnderTest = new ProgramController(_programService, _claimsService, _mapper, _validatorService);
        }

        public class GetAll : ProgramControllerIntegrationTests
        {
            [Fact]
            public async void DoRequestForAllPrograms_ReturnSuccessHttpStatusAndListViewModelList()
            {
                var result = await _classUnderTest.GetAll() as ObjectResult; ;

                result.ShouldBeOfType&lt;OkObjectResult&gt;();
                result.StatusCode.ShouldBe(200);
                result.Value.ShouldBeOfType&lt;List&lt;ListViewModel&gt;&gt;();
            }
        }

        public class Create : ProgramControllerIntegrationTests
        {
            [Fact]
            public async void DoRequestForCreateWithCorrectData_ReturnCreatedHttpStatus()
            {
                var createviewmodel = new CreateViewModel
                {
                    Name = ""Muskel Deutsche Program"",
                    Length = 1,
                    TimesPerWeek = 3,
                    Type = (byte)ProgramTypeEnum.MuscleGain
                };

                var result = await _classUnderTest.Create(createviewmodel) as ObjectResult;

                result.ShouldBeOfType&lt;OkObjectResult&gt;();
                result.StatusCode.ShouldBe(201);
            }

            [Fact]
            public async void DoRequestForCreateWithMissingData_ReturnBadRequestHttpStatus()
            {
                var createviewmodel = new CreateViewModel
                {
                    Type = (byte)ProgramTypeEnum.MuscleGain
                };

                var result = await _classUnderTest.Create(createviewmodel) as ObjectResult;

                result.ShouldBeOfType&lt;BadRequestObjectResult&gt;();
                result.StatusCode.ShouldBe(400);
            }
        }

        private ApplicationDbContext GetContextWithData()
        {
            var options = new DbContextOptionsBuilder&lt;ApplicationDbContext&gt;()
                .UseInMemoryDatabase(Guid.NewGuid().ToString())
                .Options;

            var context = new ApplicationDbContext(options);

            var programs = new List&lt;Context.Models.Program&gt;
            {
                new Context.Models.Program
                {
                    CreatedBy = ""d0806514-cbce-47b7-974f-c50f77d5e89c"",
                    CreatedDate = new DateTime(2010, 10, 10),
                    Id = 1,
                    IsActive = true,
                    IsDeleted = false,
                    Length = 1,
                    ModifiedBy = ""d0806514-cbce-47b7-974f-c50f77d5e89c"",
                    ModifiedDate = new DateTime(2010, 10, 10),
                    Name = ""Big Muscle"",
                    TimesPerWeek = 1

                },
                //new Context.Models.Program
                //{
                //    CreatedBy = ""d0806514-cbce-47b7-974f-c50f77d5e89c"",
                //    CreatedDate = new DateTime(2010, 10, 10),
                //    Id = 1,
                //    IsActive = true,
                //    IsDeleted = false,
                //    Length = 1,
                //    ModifiedBy = ""d0806514-cbce-47b7-974f-c50f77d5e89c"",
                //    ModifiedDate = new DateTime(2010, 10, 10),
                //    Name = ""Stay Fit"",
                //    TimesPerWeek = 1

                //}
            };

            context.AddRangeAsync(programs);

            context.SaveChanges();

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

<p>Problem arises at DoRequestForCreateWithCorrectData_ReturnCreatedHttpStatus method where I use context to add new item into memory DB. Same problem arises when I want to add more items into context at the same time, so I think I am doing to initialisation wrong way.</p>
",https://stackoverflow.com/questions/44551253/inmemory-dbcontext-throws-error-when-integration-testing,"['c#', 'entity-framework', 'integration-testing']",155,FALSE,1,1
Filter src/main/resources for integration testing,"<p>I am trying to filter a properties file in src/main/resources for testing only with a mock.  Next revert back to filtering for the real class.</p>

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

<p>src/main/resources/META-INF/ejb-jar.xml</p>

<p>in ejb-jar.xml</p>

<pre><code>...

&lt;ejb-link&gt;${ejb.link.class}&lt;/ejb-link&gt;
&lt;/ejb-local-ref&gt;
</code></pre>

<p>src/main/resources/config.properties</p>

<p>in config.properties:
<code>ejb.link.class = Mock</code></p>

<p>pom.xml</p>

<pre><code>        &lt;plugin&gt;
            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-resources-plugin&lt;/artifactId&gt;
            &lt;executions&gt;
                &lt;execution&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;resources&lt;/goal&gt;
                    &lt;/goals&gt;
                    &lt;id&gt;filter-resources&lt;/id&gt;
                    &lt;phase&gt;process-resources&lt;/phase&gt;
                    &lt;configuration&gt;
                        &lt;resources&gt;
                            &lt;resource&gt;
                                &lt;directory&gt;src/main/resources&lt;/directory&gt;
                                &lt;filtering&gt;true&lt;/filtering&gt;
                            &lt;/resource&gt;
                        &lt;/resources&gt;
                        &lt;filters&gt;
                            &lt;filter&gt;src/main/resources/config.properties&lt;/filter&gt;
                        &lt;/filters&gt;
                    &lt;/configuration&gt;
                &lt;/execution&gt;
            &lt;/executions&gt;
        &lt;/plugin&gt;
</code></pre>

<p>In this example, this works fine for normal build.  I would like to have a different filter for testing.  Perhaps pull from src/test/resources, and when testing is done, the normal cycle is ran with the needed filter for production.</p>

<p>I can't seem to figure out the right sequence for execution for testing.</p>

<p>Any advice is appreciated.</p>

<p>Thanks,</p>

<p>Abe</p>
",https://stackoverflow.com/questions/44870432/filter-src-main-resources-for-integration-testing,"['java', 'maven', 'testing', 'ejb-3.1']",80,FALSE,1,0
corda M13.0 - Integration Testing of an Oracle,"<p>I followed the oracle-example to create a dummy FX rate oracle.  It passed the MockNetwork tests.  Now in the integration test via driver, I get the following FlowSessionException complaining ""flow has not been registered"". 
My other integration tests don't need to register any flows.  Is it peculiar to the oracle service?
How do I register an initiating flow in the test?</p>

<pre><code>net.corda.core.flows.FlowSessionException: Party CN=FX Rate Oracle,O=FX Rate Oracle,L=San Francisco,C=US,OU=argent.fxrate_oracle rejected session request: argent.flow.FXRateQueryFlow has not been registered
    at net.corda.node.services.statemachine.FlowStateMachineImpl.waitForConfirmation(FlowStateMachineImpl.kt:266) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.startNewSession(FlowStateMachineImpl.kt:326) ~[corda-node-0.13.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.sendAndReceive(FlowStateMachineImpl.kt:169) ~[corda-node-0.13.0.jar:?]
    at net.corda.core.internal.FlowStateMachine$DefaultImpls.sendAndReceive$default(FlowStateMachine.kt:22) ~[corda-core-0.13.0.jar:?]
    at net.corda.core.flows.FlowLogic.sendAndReceive(FlowLogic.kt:89) ~[corda-core-0.13.0.jar:?]
    at argent.flow.FXRateQueryFlow.call(FXRateQueryFlow.kt:20) ~[service-interface-0.1.jar:?]
    at argent.flow.FXRateQueryFlow.call(FXRateQueryFlow.kt:14) ~[service-interface-0.1.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:107) [corda-node-0.13.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:39) [corda-node-0.13.0.jar:?]
    at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1067) [quasar-core-0.7.6-jdk8.jar:0.7.6]
    at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:767) [quasar-core-0.7.6-jdk8.jar:0.7.6]
    at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) [quasar-core-0.7.6-jdk8.jar:0.7.6]
    at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) [quasar-core-0.7.6-jdk8.jar:0.7.6]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_131]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_131]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_131]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_131]
    at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:69) [corda-node-0.13.0.jar:?]
</code></pre>
",https://stackoverflow.com/questions/45038593/corda-m13-0-integration-testing-of-an-oracle,['corda'],142,FALSE,1,1
Record/Revert DynamoDB state for integration testing,"<p>I want to write integration testing for my API Gateway which is using DynamoDB as backend. I was wondering if there is a method/framework/libraries which provides flexibility to record DynamoDB state before tests and revert it back to original state after the tests? </p>

<p>Ideally, I want something which can keep track changes made in DynamoDB since the beginning of tests and revert all those changes once the test is completed. </p>
",https://stackoverflow.com/questions/43823072/record-revert-dynamodb-state-for-integration-testing,"['integration-testing', 'amazon-dynamodb']",1493,TRUE,1,2
Integration Testing Approach for Code C/C++,"<p>I have seen this <a href=""https://stackoverflow.com/questions/1439172/testing-code-in-c-c"">post</a> about Unit Testing for C/C++. I have heard that gtest can be used for Integration Testing. What is the best approach to do Integration Tests? I am afraid that this could replicate Unit/System tests so I am not sure what test technique should I use for C embedded systems.</p>
",https://stackoverflow.com/questions/45989699/integration-testing-approach-for-code-c-c,"['c', 'integration-testing', 'googletest']",4137,FALSE,1,0
Getting parameters in integration testing MSTesting C#,"<p>I need to get a lot of parameters to dynamically build a test method. My limits is it has to be in MSTest and C#. </p>

<p>What I'm thinking is something of the likes of: </p>

<pre><code>[TestMethod]
public void test1 (int x, int y, string url, double l)
{
     // Use parameters here
}
</code></pre>

<p>I know this is not possible, I get that. But that is ultimately what I need to get.</p>

<p>Can anyone share some insight on this?</p>
",https://stackoverflow.com/questions/42387031/getting-parameters-in-integration-testing-mstesting-c,"['c#', 'testing', 'integration-testing', 'mstest']",286,TRUE,1,1
Laravel 5.4 - integration testing role middleware fails,"<p>I'm trying to test some middleware that checks to see if a user has <code>x</code> role with Laravel 5.4/PHPUnit. The role functionality works fine in the browser, but I can't seem to get my tests to pass (I get 403's as expected with someone without the required role) with the following code:</p>

<pre><code>public function testSuperAdminRoleRoute()
{
    $admin = factory(User::class)-&gt;create();
    $adminRole = \HttpOz\Roles\Models\Role::whereSlug('super.admin')-&gt;first();

    $admin-&gt;detachAllRoles();
    $admin-&gt;attachRole($adminRole);

    $response = $this-&gt;actingAs($admin)
                     -&gt;get('/super-admin-only')
                     -&gt;assertStatus(200);
}
</code></pre>

<p>When I <code>dd($admin-&gt;roles)</code> I do indeed see the correct role, but I think I'm missing something maybe a limitation within Laravel/PHPUnit. I have previously tested this sort of functionality in my acceptance tests and had it work.</p>

<p>Any advice is much appreciated!</p>
",https://stackoverflow.com/questions/44218439/laravel-5-4-integration-testing-role-middleware-fails,"['php', 'laravel', 'phpunit', 'integration-testing']",342,TRUE,0,1
Hardware Integration Testing in Xamarin Test Cloud,"<p>We would like to have functional tests which require our app to connect with external hardware device.</p>

<p>We know that we can record the test cases and run then with mobile device connected via USB from Visual Studio.</p>

<p>But, can anybody confirm if Xamarin Test Cloud provides any way of setting up Test Server with set of mobile devices to perform Hardware connectivity/bluetooth communication testing with Mobile App under Test?</p>

<p>Thanks
Dhavan</p>
",https://stackoverflow.com/questions/45432446/hardware-integration-testing-in-xamarin-test-cloud,"['xamarin', 'xamarin.ios', 'xamarin.android', 'xamarin-test-cloud']",105,TRUE,0,1
Junit Integration Testing in 3 layer Architecture,"<p>So i have to write a integration test for my project which is about managing employee and organized by 3 layer architecture , it just have 3 functionality insert, update, delete. Since i have lack experience in testing so i'm confused one thing that if i write test for one functionality like insert employee, which class i have to call to test for that functionality , Business Layer or Data Access Layer ??
Thanks for your answers
<a href=""https://i.stack.imgur.com/sN8Ca.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/sN8Ca.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/47757409/junit-integration-testing-in-3-layer-architecture,"['java', 'junit', 'integration-testing']",113,FALSE,0,1
Integration Testing Data Access Code For Sql,"<p>I have a class named <strong><em>Database</em></strong>  that implements following interface ;</p>

<pre><code> public interface IDatabase
{
    int ExecuteNonQuery(string command, CommandType commandType, Dictionary&lt;string, object&gt; parameters);
}
</code></pre>

<p>As the name indicates <strong><em>ExecuteNonQuery</em></strong> function executes non-query database commands in a provider agnostic way.</p>

<p>I need to write integration test for this class, and so far I've written an integration test for <strong>Sql Server Compact Edition</strong>  which passes the test.</p>

<p>Here is the integration test code ;</p>

<pre><code>public class DatabaseIntegrationTests
{
    private readonly string CurrentDir;
    private readonly string SqlCeDbPath;

    public DatabaseIntegrationTests()
    {
        CurrentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        SqlCeDbPath = CurrentDir + @""\TestDb.sdf"";
    }

    [Fact]
    public void ExecuteNonQuery_SqlServerCE_Should_Execute()
    {
        var dbConfFunc = this.InitializeSqlServerCeInstance();
        Database database = new Database(dbConfFunc);
        database.ExecuteNonQuery(""CREATE TABLE Test([ID] [bigint] IDENTITY(1,1) NOT NULL,[Message] [nvarchar](255) NULL)"",
            CommandType.Text, null);

        var parameters = new Dictionary&lt;string, object&gt;();
        parameters.Add(""@message"", ""Hello World!"");
        database.ExecuteNonQuery(""INSERT INTO Test(Message) VALUES(@message)"",
            CommandType.Text, parameters);

        CleanUpSqlServerCe();
    }
    private void CleanUpSqlServerCe()
    {
        if (File.Exists(SqlCeDbPath))
            File.Delete(SqlCeDbPath);
    }
    private Func&lt;DbConnectionConfiguration&gt; InitializeSqlServerCeInstance()
    {
        string connectionString = ""Data Source="" + CurrentDir + @""\ASTest.sdf;Persist Security Info=False"";

        CleanUpSqlServerCe();

        SqlCeEngine engine = new SqlCeEngine(connectionString);
        engine.CreateDatabase();

        return () =&gt;
       {
           return new DbConnectionConfiguration()
           {
               DataProvider = ""System.Data.SqlServerCe.4.0"",
               ConnectionString = connectionString
           };
       };
    }
}
</code></pre>

<p>My question is , how can write integration test for this class for  MySql and Sql Server database providers? 
What is the most practical way to write integration test for this class to test it for both MySql and Sql Server databases?</p>
",https://stackoverflow.com/questions/43850279/integration-testing-data-access-code-for-sql,"['c#', '.net', 'testing', 'integration-testing']",243,TRUE,0,1
Failover Integration Testing of Kafka/Spring Integration,"<p>I am looking at <strong><em>two</em></strong> scenarios, working on top of Spring Integration with Kafka:</p>

<ol>
<li><em>Happy path</em> - the channel flows correctly and passes it's payload to the out-bound channel successfully</li>
<li><em>Alternate case</em> - the channel flows correctly but the out-bound channel is <strong>down</strong></li>
</ol>

<p>My plan here is to use <strong>AOP</strong> on the <code>KafkaTemplate</code>, that throws an Exception when it is called by any send methods. This will then be returned to the <strong>Error Channel</strong>.</p>

<p>I was wondering what other (<strong><em>simpler</em></strong> &amp; unobtrusive!) test techniques, that may be used to handle an unavailable out-bound channel?</p>

<p><em>Bonus points</em> for ApplicationContext (i.e. XML) solutions, rather than annotation based!</p>
",https://stackoverflow.com/questions/46794044/failover-integration-testing-of-kafka-spring-integration,"['java', 'spring', 'apache-kafka', 'spring-integration']",169,FALSE,0,1
golang should this be an integration testing?,"<p>I have a method which implements the a database interface, that method inserts an 'object' into the database.</p>

<pre><code>type database interface {
    createLog(logDoc) (bool, error)
}


type mongo struct {
    database   string
    collection string
}

func (m mongo) createLog(l logDoc) (bool, error) {

    s, err := mgo.Dial(""mongo"")

    defer s.Close()

    if err != nil {
        return false, err
    }

     err = s.DB(m.database).C(m.collection).Insert(l)
     if err != nil {
        return false, err
     }

     return true, nil
}
</code></pre>

<p>I want to be able to test the createLog method, how can I do this? should it be an integration test? if so what would be the your approach?</p>

<p>Thank you in advance</p>
",https://stackoverflow.com/questions/45658938/golang-should-this-be-an-integration-testing,"['unit-testing', 'testing', 'go', 'integration-testing']",759,FALSE,-1,1
Kotlin + JUnit + postgres for integration testing: leaked connections,"<p>I set up a test class that runs 13 integration tests. All of the tests involve 1 database, 1 schema and 3 tables in the schema. The test class is set up so that I create the test database with <code>@BeforeClass</code> and delete the test database with <code>@AfterClass</code>. In the <code>setUp</code> phase for each test, I migrate the schema and populate the tables with artificial data. Then in the <code>tearDown</code> phase I remove the schema. In each test, I run my test logic against the test database:</p>

<pre class=""lang-kotlin prettyprint-override""><code>class MyTest {
  companion object {
    private val helper = MyHelper()
    @BeforeClass @JvmStatic
    fun createTestDatabase() {
        helper.createTestDatabase()
    }
    @AfterClass @JvmStatic
    fun removeTestDatabase() {
        helper.deleteTestDatabase()
    }
  }
  @Before
  fun setUp(){
    // migrate the schema and populate the tables with artificial data
    helper.migrate()
    helper.populate()
  }

  @After
  fun tearDown() {
    // remove the schema
    helper.removeSchema()
  }
  @Test MyFirstTest() {
    // populate the tables with artificial data
    ... // test logic
  }
  ...
}
</code></pre>

<p>The database manipulations are all implemented in <code>MyHelper</code> class. In particular, I have one function in <code>MyHelper</code> that executes a query string:</p>

<pre class=""lang-kotlin prettyprint-override""><code>class MyHelper {
  protected val POSTGRES_USER = ""postgres""
  protected val POSTGRES_HOST = ""localhost""
  protected val POSTGRES_PORT = 5432
  protected val POSTGRES_TEST_DATA_DATABASE = ""my_database_test""
  protected val POSTGRES_TEST_DATA_SCHEMA = ""my_schema""
  protected val POSTGRES_DEFAULT_DATABASE = ""postgres""
  protected val POSTGRES_DEFAULT_SCHEMA = ""postgres""

  protected val graphDataTables = listOf(""my_table_1"", ""my_table_2"", ""my_table_3"")

  val databases = listOf(POSTGRES_DEFAULT_DATABASE, POSTGRES_TEST_DATA_DATABASE)
  val dataSources = databases.associateBy({it}, { getDataSource(it)})

  fun getDataSource(database: String): PGSimpleDataSource {
      val ds = PGSimpleDataSource()
      val url = ""jdbc:postgresql://$POSTGRES_HOST:$POSTGRES_PORT/$database""
      ds.setUrl(url)
      ds.setUser(POSTGRES_USER)
      return ds
  }

  fun executeQuery(sqlQuery: String,
                   database: String = this.POSTGRES_DEFAULT_DATABASE,
                   schema: String = this.POSTGRES_DEFAULT_SCHEMA
  ): Unit {
      val ds = dataSources[database]!!
      ds.currentSchema = schema

      ds.connection.use {
          it.createStatement().use {
              it.execute(sqlQuery)
          }
      }
  }
  ...
}
</code></pre>

<p>The function <code>MyHelper.populate()</code> uses the <code>executeQuery</code> function to insert data into the tables. </p>

<p>My problem is that it seems that I have many unclosed connections (leaked connections). If I keep the # of tests under 10, then all tests pass without a problem. As soon as I pass 10, I get errors like the following for tests 11 and up:</p>

<pre><code>Nov 09, 2017 11:31:55 AM org.postgresql.Driver connect
SEVERE: Connection error: 
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already
    at org.postgresql.Driver$ConnectThread.getResult(Driver.java:401)
    at org.postgresql.Driver.connect(Driver.java:259)
    ...
</code></pre>

<p>for the tests that got run after the 10th. And the last stack in the log points to the <code>ds.connection.use {</code> line in the function <code>executeQuery</code>. </p>

<p>However, if I move the <code>helper.createTestDatabase()</code> out of the companion object, and put it in the init block for <code>MyTest</code>, like so:</p>

<pre class=""lang-kotlin prettyprint-override""><code>class MyTest {
  companion object {
    private val helper = MyHelper()
  }
  init {
    helper.createTestDatabase()
  }
  ...
}
</code></pre>

<p>then I don't get any error even if the # of my tests are over 10. The problem I see with this is that now I have a test database created in my postgres docker container and it still exists after I'm done with the integration tests. I have no idea how to call <code>removeTestDatabase</code> now. </p>

<p>I run my tests in debug mode and stopped in the middle of the 10th test, then with</p>

<pre><code>select * from pg_stat_activity;
</code></pre>

<p>I can see that there are many idle connections (almost 100) in the first scenario. In the 2nd scenario, I have only 10 idle connections in the middle of the 10th test (I'd like the number of idle connections to be 0, of course). My understanding is that my default postgres setting is that <code>max_connections</code> is set to 100. That's why I get the error when I have more than 10 tests in the first scenario. But I have no idea how I am creating idle connections. </p>
",https://stackoverflow.com/questions/47210328/kotlin-junit-postgres-for-integration-testing-leaked-connections,"['postgresql', 'junit', 'kotlin', 'integration-testing']",1000,FALSE,4,0
how to use embedded ElasticSearch for integration testing,"<p>I am following this tutorials </p>

<ol>
<li><a href=""https://orrsella.com/2014/10/28/embedded-elasticsearch-server-for-scala-integration-tests/"" rel=""nofollow noreferrer"">https://orrsella.com/2014/10/28/embedded-elasticsearch-server-for-scala-integration-tests/</a></li>
</ol>

<p>All I am trying to follow the link because I am using ELasticSearch <code>1.6.0</code> but it's using NodeClient and I want to use <code>transportClient</code> but I am getting exception </p>

<pre><code> org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: []
[info]   at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:305)
[info]   at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:200)
[info]   at org.elasticsearch.client.transport.support.InternalTransportIndicesAdminClient.execute(InternalTransportIndicesAdminClient.java:86)
[info]   at org.elasticsearch.client.support.AbstractIndicesAdminClient.create(AbstractIndicesAdminClient.java:367)
[info]   at org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder.doExecute(CreateIndexRequestBuilder.java:250)
[info]   at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:91)
[info]   at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:65)
[info]   at testcontrollers.campaign.ElasticsearchServer.createAndWaitForIndex(ElasticsearchServer.scala:40)
[info]   at testcontrollers.campaign.CampaignTestSearch.&lt;init&gt;(CampaignTestSearch.scala:41)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
</code></pre>

<p>here is the code </p>

<pre><code>class ElasticsearchServer {
  val log = LoggerFactory.getLogger(this.getClass)
  private val clusterName = ""testcluster""
  private val dataDir = Files.createTempDirectory(""elasticsearch_test_data_"").toFile
  private val settings = ImmutableSettings.settingsBuilder
    .put(""path.data"", dataDir.toString)
    .put(""cluster.name"", clusterName)
    .put(""node.local"",true)
    .build

  def client: TransportClient ={
    val client=new TransportClient(settings)
    .addTransportAddress(new InetSocketTransportAddress(""127.0.0.1"", 9300))
   client
  }
  def stop(): Unit = {
    client.close();

    try {
      FileUtils.forceDelete(dataDir)
    } catch {
      case e: Exception =&gt; // dataDir cleanup failed
    }
  }

    def createAndWaitForIndex(index: String): Unit = {
      client.admin.indices.prepareCreate(index).execute.actionGet()
      client.admin.cluster.prepareHealth(index).setWaitForActiveShards(1).execute.actionGet()
    }
}

class CampaignTestSearch extends PlaySpec{
  val server = new ElasticsearchServer
  server.createAndWaitForIndex(""arteciatetestdb"")
val client=server.client

val response = client.prepareSearch(""dbtest"")
      .setTypes(CAMPAIGN_COLLECTION_NAME)
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .addFields(""uuid"",""campaignName"",""artworkID"",""activationDate"",""_source"")
      .setQuery(query)
      .execute()
      .actionGet()
  }
</code></pre>
",https://stackoverflow.com/questions/45839904/how-to-use-embedded-elasticsearch-for-integration-testing,"['java', 'scala', 'elasticsearch', 'integration-testing', 'elasticsearch-1.6.0']",8451,TRUE,4,2
how to do Integration testing in microservices architecture,"<p>I was looking for patterns/best practice for doing integration testing in microservices.  Below is quick description of my context.</p>

<ol>
<li>microservice A  depends on<br>
a. azureAD for authentication<br>
b. Microservice B for authorization</li>
<li>microservice B talks to azure sql Db to CRUD for user/roles/permissions + exposes endpoints to check permission which is used by 1.  this service is also protected by azure AD authentication</li>
</ol>

<p>What is the best approach to create integration test for such a case. ? Any references or guidance welcome. Some questions :</p>

<p>a. what to mock , what not to mock<br>
b. setup teardown strategy<br>
c. others  </p>
",https://stackoverflow.com/questions/42354108/how-to-do-integration-testing-in-microservices-architecture,"['c#', 'azure', 'asp.net-web-api', 'integration-testing', 'microservices']",1877,TRUE,4,1
Java Spring app run DynamoDBEmbedded for integration testing?,"<p>Is it possible to run an embedded instance of DynamoDB within a Spring application to be used by integration tests similar to what embedded-redis allows? <a href=""https://github.com/kstyrc/embedded-redis"" rel=""nofollow noreferrer"">https://github.com/kstyrc/embedded-redis</a></p>

<p>A sample blob by AWS seems to indicate this is possible: <a href=""https://github.com/awslabs/aws-dynamodb-examples/blob/master/src/test/java/com/amazonaws/services/dynamodbv2/local/embedded/DynamoDBEmbeddedTest.java"" rel=""nofollow noreferrer"">https://github.com/awslabs/aws-dynamodb-examples/blob/master/src/test/java/com/amazonaws/services/dynamodbv2/local/embedded/DynamoDBEmbeddedTest.java</a></p>

<p>However, the documentation is scant and when attempting to set up the Embedded DynamoDB in the way shown I get the following error:</p>

<pre><code>AmazonDynamoDB ddb = DynamoDBEmbedded.create().amazonDynamoDB();
</code></pre>

<p>Throws:</p>

<pre><code>Caused by: java.lang.NullPointerException
    at com.amazonaws.services.dynamodbv2.local.shared.access.sqlite.SQLiteDBAccess.initializeMetadataTables(SQLiteDBAccess.java:389)
    at com.amazonaws.services.dynamodbv2.local.shared.access.sqlite.SQLiteDBAccess.&lt;init&gt;(SQLiteDBAccess.java:225)
    at com.amazonaws.services.dynamodbv2.local.shared.access.sqlite.SQLiteDBAccess.&lt;init&gt;(SQLiteDBAccess.java:194)
    at com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded.create(DynamoDBEmbedded.java:45)
    at com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded.create(DynamoDBEmbedded.java:35)
    at com.wdpr.keyring.entitlements.EmbeddedDynamoDBConfig.embeddedDynamoDB(EmbeddedDynamoDBConfig.java:26)
</code></pre>

<p>Essentially for the Spring application I would be registering the <code>AmazonDynamoDB</code> instance created by <code>DynamoDBEmbedded.create().amazonDynamoDB();</code> as my bean to be used in the TEST application context like so:</p>

<pre><code>@TestConfiguration
public class EmbeddedDynamoDBConfig {

    @Bean
    AmazonDynamoDB embeddedDynamoDB() {
        return DynamoDBEmbedded.create().amazonDynamoDB();
    }
}
</code></pre>

<p>If this is not possible, what are some other potential solutions?</p>
",https://stackoverflow.com/questions/47126180/java-spring-app-run-dynamodbembedded-for-integration-testing,"['java', 'spring', 'amazon-dynamodb', 'integration-testing']",3076,TRUE,3,1
Integration Testing with AutoMapper fails to initialise configuration,"<p><strong>Frameworks &amp; Packages</strong>  </p>

<pre class=""lang-cs prettyprint-override""><code>.NETCoreApp 1.1
Xunit 2.2.0
AutoMapper 6.0.2
Microsoft.AspNetCore.TestHost 1.1.1
Microsoft.NET.Test.Sdk 15.0.0
</code></pre>

<p><strong>Integration Test</strong></p>

<pre class=""lang-cs prettyprint-override""><code>public class ControllerRequestsShould
{
    private readonly TestServer _server;
    private readonly HttpClient _client;

    public ControllerRequestsShould()
    {
        _server = new TestServer(new WebHostBuilder()
            .UseContentRoot(Constants.apiProjectRoot)
            .UseStartup&lt;Startup&gt;()
            .UseEnvironment(Constants.testingEnvironment));
        _client = _server.CreateClient();
        _client.BaseAddress = new Uri(Constants.localHostUri);
    }

    [Fact]
    public async Task CreateAnEntity()
    {
        // Arrange
        var entityForCreationDto = new entityForCreationDto { Code = ""00001"", Name = ""Entity One"" };
        var jsonContent = JsonConvert.SerializeObject(entityForCreationDto);
        var stringContent = new StringContent(jsonContent);
        stringContent.Headers.ContentType = new MediaTypeHeaderValue(""application/json"");

        // Act
        var response = await _client.PostAsync(""/api/controller"", stringContent);
        response.EnsureSuccessStatusCode();

        // Assert
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
}
</code></pre>

<p><strong>Startup.cs</strong></p>

<pre class=""lang-cs prettyprint-override""><code>public class Startup
{
    public IConfigurationRoot Configuration { get; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile(""appsettings.json"", optional: true, reloadOnChange: true)
            .AddJsonFile($""appsettings.{env.EnvironmentName}.json"", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services
        services.AddMvc(setupAction =&gt;
        {
            setupAction.ReturnHttpNotAcceptable = true;
            setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            setupAction.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());
        });

        // Db context configuration
        var connectionString = Configuration[""ConnectionStrings:DefaultConnection""];
        services.AddDbContext&lt;YourContext&gt;(options =&gt;
        {
            options.UseSqlServer(connectionString);
        });

        // Register services for dependency injection
        services.AddScoped&lt;IYourRepository, YourRepository&gt;();

        services.AddSingleton&lt;IActionContextAccessor, ActionContextAccessor&gt;();

        services.AddScoped&lt;IUrlHelper, UrlHelper&gt;(implementationFactory =&gt;
        {
            var actionContext =
                implementationFactory.GetService&lt;IActionContextAccessor&gt;().ActionContext;
            return new UrlHelper(actionContext);
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug(LogLevel.Information);
        loggerFactory.AddNLog();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler(appBuilder =&gt;
            {
                appBuilder.Run(async context =&gt;
                {
                    var exceptionHandlerFeature = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
                    if (exceptionHandlerFeature != null)
                    {
                        var logger = loggerFactory.CreateLogger(""Global exception logger"");
                        logger.LogError(500,
                            exceptionHandlerFeature.Error,
                            exceptionHandlerFeature.Error.Message);
                    }

                    context.Response.StatusCode = 500;
                    await context.Response.WriteAsync(""An unexpected fault happened.  Try again later"");
                });
            });
        }

        Mapper.Initialize(cfg =&gt;
        {
            cfg.CreateMap&lt;DataStore.Entities.Entity, Models.EntityDto&gt;();
            cfg.CreateMap&lt;Models.EntityDto, DataStore.Entities.Entity&gt;();
            cfg.CreateMap&lt;Models.EntityForCreationDto, DataStore.Entities.Entity&gt;();
            cfg.CreateMap&lt;DataStore.Entities.Entity, Models.EntityForCreationDto&gt;();
        });

        app.UseMvc();
    }
</code></pre>

<p><strong>Problem</strong><br>
The integration test fails after the controller method is invoked:</p>

<pre class=""lang-cs prettyprint-override""><code>var response = await _client.PostAsync(""/api/controller"", stringContent);
</code></pre>

<p>It fails because AutoMapper has not been initialised.
The way I understood this was that since the <code>TestServer</code> has the <code>UseStartup</code> method, it should use all the services configured in the api <code>Startup.cs</code> class (the <code>UseContentRoot</code> is pointing to my api project root)</p>

<p>This clearly isn't happening.  Could someone show me how I need to configure the <code>TestServer</code> so that the AutoMapper configuration is picked up correctly please?</p>
",https://stackoverflow.com/questions/43630620/integration-testing-with-automapper-fails-to-initialise-configuration,"['c#', 'integration-testing', 'asp.net-core-webapi', 'xunit2', 'automapper-6']",2116,TRUE,3,3
Vuejs 2 two connected components unit/integration testing,"<p>I have 2 Vuejs components that are connected to each other. The first component is updating data in the second one. What is the best approach for integration testing? I am using vuejs 2. </p>

<p>VoucherComponent:</p>

<pre><code>import Store from '../store';
import Ajax from '../_helpers/ajax';
const Voucher =  {
name: 'voucher',
props: ['id'],
template: '',
data () {
    return {
        voucherCode: null,
        priceDetails: Store.priceDetails,
        vouchers: Store.vouchers
    }
},
beforeCreate() {
    Store.vouchers = []
},
methods: {
    validateVoucher() {

        let totalPrice      = Store.total;
        let vouchers        = this.vouchers;
        let voucherCode     = this.voucherCode;
        let id         = this.id;
        let priceDetails    = this.priceDetails;


        let voucher = new Ajax('/vouchers/redeem/' + voucherCode + '/' + id + '/' + totalPrice + '/', 'GET');
        if (!this.checkVoucherPriceDetails()) {
            voucher.ajaxCall(function (response) {
                if (!response.error) {
                    vouchers.push({
                        code: voucherCode,
                        value: parseFloat(response.data.discount).toFixed(2),
                        type: 'voucher',
                        name: 'voucher',
                        description: 'Your voucher code: ' + voucherCode
                    });

                    priceDetails.push({
                        code: voucherCode,
                        price: parseFloat((-1.00 * response.data.discount)).toFixed(2),
                        description: 'Your voucher code: ' + voucherCode,
                        type: 'voucher'
                    });

                } else {
                    return false;
                }
            });
        }
    },
    removeVoucher(voucher) {
        this.voucherCode = voucher.code;
        this.clearVouchersFromPriceDetails();
        var stringifyVoucher = JSON.stringify(voucher);
        for (var i = 0, len = this.vouchers.length; i &lt; len; i++) {
            if (stringifyVoucher === JSON.stringify(this.vouchers[i])) {
                this.vouchers.splice(i, 1);
                break;
            }
        }
        // return true;
    },
    clearVouchersFromPriceDetails() {
        for (var i = this.priceDetails.length - 1; i &gt;= 0; i--) {
            if (this.priceDetails[i].code === this.voucherCode) {
                this.priceDetails.splice(i, 1);
            }
        }
    },
    checkVoucherPriceDetails() {
        for (var i = this.priceDetails.length - 1; i &gt;= 0; i--) {
            if (this.priceDetails[i].code === this.voucherCode) {
                return true;
            }
        }

        return false;
    }
},
mounted () {
    Store.debug &amp;&amp; console.log(""Init voucher component"");
}
};


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

<p>PriceDetailsComponent:</p>

<pre><code>import Store from '../store';
const PriceDetails = {
name: 'price-details',
props: ['price','fee'],
data() {
    return {
        priceDetails: Store.priceDetails,
        store: Store
    }
},
created() {
    this.priceDetails.push({
        price: this.price.toFixed(2),
        description: ""Buchung Preis"",
        type: 'booking'
    });
    this.priceDetails.push({
        price: this.fee.toFixed(2),
        description: ""Buchungsgebühren"",
        type: 'booking_fee'
    });
},
computed: {
    totalPrice() {
        let total = 0.00;
        let insurancePrice = 0.00;
        for (var detailKey in this.priceDetails) {
            var detail = this.priceDetails[detailKey];
            total += parseFloat(detail.price);
            if (detail.type == 'insurance') {
                insurancePrice = detail.price;
            }
            this.store.total = total;
        }
        return parseFloat(total).toFixed(2);
    }
},
mounted() {
    Store.debug &amp;&amp; console.log(""Init price-details"");
}
};
export default PriceDetails;
</code></pre>

<p>Store:</p>

<pre><code>const Store = {
    debug: true,
    priceDetails: [],
    total: 0.00
};

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

<p>Thanks a lot!</p>
",https://stackoverflow.com/questions/42790270/vuejs-2-two-connected-components-unit-integration-testing,"['javascript', 'unit-testing', 'testing', 'vue.js', 'integration-testing']",104,FALSE,1,0
Switching from .findall() to .query() breaks integration testing,"<p>I have a component that calls something like:</p>

<pre><code>this.get('store')
  .findAll('calendar-event')
  .then((data) =&gt; {
    // do stuff
  });
</code></pre>

<p>However, when I replace <code>findAll()</code> with <code>query()</code> it breaks my integration testing.  </p>

<pre><code>this.get('store')
  .query('calendar-event', { some_stuff: [596] })
  .then((data) =&gt; {
    // do stuff
  });
</code></pre>

<p>The application in the web browser via <code>ember server</code> continues to function correctly.  However: no luck with integration testing.  Error I get is: <strong>TypeError: Cannot read property 'setObjects' of null</strong></p>

<h3>Integration test looks like:</h3>

<pre><code>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import moment from 'moment';

import startMirage from '../../helpers/setup-mirage-for-integration';

moduleForComponent('main-calendar', 'Integration | Component | main calendar', {
  integration: true,
  beforeEach() {
    startMirage(this.container);
  },
  afterEach() {
    window.server.shutdown();
  }
});

test('it renders', function (assert) {
  this.render(hbs`{{main-calendar}}`);
  assert.equal(this.$('.col-sm.text-center').text().trim(), moment().format('MMMM YYYY'));
});
</code></pre>

<p>Any ideas why it would render with the server but not on the integration testing side of things.</p>
",https://stackoverflow.com/questions/45475709/switching-from-findall-to-query-breaks-integration-testing,"['ember.js', 'ember-data', 'ember-cli-mirage']",95,FALSE,1,0
"Java integration testing (DAO layer, generic CRUD operations)","<p>I have been looking for a refined way to create integration tests for DAO layer (Java, Spring, Hibernate), mostly for generic CRUD operations (readAll(), getById(), insert(), update(), delete(). etc.), for several months. What I've found so far is either 1) too laborious approach with the amount of code comparable with real source code or 2) Too complicated/unreadable/inflexible approach to do it.
One attempt that I've undertaken so far is the following:
If we have say generic DAO interface like this one:</p>

<pre><code>public interface GenericDAO&lt;T&gt; {
    Long insert(T t);
    void update(T t);
    List&lt;T&gt; getAll();
    T getById(Long id);
    void delete(T t);
 }
</code></pre>

<p>Then we could propose some template method (because all the tests are performed randomly by default) to perform all those CRUD operations, which is applicable to every class:</p>

<pre><code>@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={""/test-context.xml""})
public abstract class AbstractDAOTest {

    @Test
    public void test() {
            insert();
            read();
            readAll();
            update();
            delete();
    }

    protected abstract void insert();

    protected abstract void read();

    protected abstract void readAll();

    protected abstract void update();

    protected abstract void delete();
</code></pre>

<p>}</p>

<p>Then we have Spring's test config with sample data and implement all these methods in real class-successor.</p>

<p>This is still not nice to me. (only one actual method to test, time-consuming to create test-context, etc.)</p>

<p>So, what is the most recognisible and triend-and-true approcah to create integration tests for DAO layer? Thank you in advance.</p>
",https://stackoverflow.com/questions/42644299/java-integration-testing-dao-layer-generic-crud-operations,"['spring', 'hibernate', 'testing', 'junit']",577,FALSE,1,0
Integration testing and JNDI resource injection with Weld,"<p>I want to test that a DAO/repository works properly with a test database (integration test). In the DAO I inject a JNDI datasource with the resource annotation:</p>

<pre><code>public class SomeDAO {

    @Resource(lookup = ""java:comp/env/ds"")
    private DataSource dataSource;
    ...
}
</code></pre>

<p>I don't want to use any server during the test, I just want to create a JNDI resource in some way and make Weld discover it and inject it.</p>

<p>Currently I am trying to achieve this using the <a href=""https://github.com/h-thurow/Simple-JNDI"" rel=""nofollow noreferrer"">Simple-JNDI</a> library: when I only test that the InitialContext contains the datasource it works, but when I test the DAO, Weld doesn't find the datasource.  </p>

<p>How to create JNDI resources for Weld to inject, or how to make it work with Simple-JNDI?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/41940685/integration-testing-and-jndi-resource-injection-with-weld,"['integration-testing', 'jndi', 'weld', 'jboss-weld']",621,FALSE,1,0
Reconfigure dependencies when Integration testing ASP.NET Core Web API and EF Core,"<p>I'm following this tutorial<br>
<a href=""http://www.davepaquette.com/archive/2016/11/27/integration-testing-with-entity-framework-core-and-sql-server.aspx"" rel=""noreferrer"">Integration Testing with Entity Framework Core and SQL Server</a></p>

<p>My code looks like this</p>

<p><strong>Integration Test Class</strong></p>

<pre><code>public class ControllerRequestsShould : IDisposable
{
    private readonly TestServer _server;
    private readonly HttpClient _client;
    private readonly YourContext _context;

    public ControllerRequestsShould()
    {
        // Arrange
        var serviceProvider = new ServiceCollection()
            .AddEntityFrameworkSqlServer()
            .BuildServiceProvider();

        var builder = new DbContextOptionsBuilder&lt;YourContext&gt;();

        builder.UseSqlServer($""Server=(localdb)\\mssqllocaldb;Database=your_db_{Guid.NewGuid()};Trusted_Connection=True;MultipleActiveResultSets=true"")
            .UseInternalServiceProvider(serviceProvider);

        _context = new YourContext(builder.Options);
        _context.Database.Migrate();

        _server = new TestServer(new WebHostBuilder()
            .UseStartup&lt;Startup&gt;()
            .UseEnvironment(Environment.GetEnvironmentVariable(""ASPNETCORE_ENVIRONMENT"")));
        _client = _server.CreateClient();
    }

    [Fact]
    public async Task ReturnListOfObjectDtos()
    {
        // Arrange database data
        _context.ObjectDbSet.Add(new ObjectEntity{ Id = 1, Code = ""PTF0001"", Name = ""Portfolio One"" });
        _context.ObjectDbSet.Add(new ObjectEntity{ Id = 2, Code = ""PTF0002"", Name = ""Portfolio Two"" });

        // Act
        var response = await _client.GetAsync(""/api/route"");
        response.EnsureSuccessStatusCode();


        // Assert
        var result = Assert.IsType&lt;OkResult&gt;(response);            
    }

    public void Dispose()
    {
        _context.Dispose();
    }
</code></pre>

<p>As I understand it, the <code>.UseStartUp</code> method ensures the <code>TestServer</code> uses my startup class</p>

<p>The issue I'm having is that when my Act statement is hit</p>

<pre><code>var response = await _client.GetAsync(""/api/route"");
</code></pre>

<p>I get an error in my startup class that the connection string is null.  I think My understanding of the problem is that when my controller is hit from the client it injects my data repository, which in turn injects the db context.</p>

<p>I think I need to configure the service as part of the <code>new WebHostBuilder</code> section so that it used the context created in the test. But I'm not sure how to do this.</p>

<p><strong>ConfigureServices method in Startup.cs</strong></p>

<pre><code>        public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services
        services.AddMvc(setupAction =&gt;
        {
            setupAction.ReturnHttpNotAcceptable = true;
            setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            setupAction.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());
        });

        // Db context configuration
        var connectionString = Configuration[""ConnectionStrings:YourConnectionString""];
        services.AddDbContext&lt;YourContext&gt;(options =&gt; options.UseSqlServer(connectionString));

        // Register services for dependency injection
        services.AddScoped&lt;IYourRepository, YourRepository&gt;();
    }
</code></pre>
",https://stackoverflow.com/questions/43543319/reconfigure-dependencies-when-integration-testing-asp-net-core-web-api-and-ef-co,"['c#', 'asp.net-core', 'integration-testing', 'entity-framework-core', 'xunit2']",19603,TRUE,26,2
Integration testing with Python unittest: how to improve granularity?,"<p>I have a single end-to-end Selenium integration test which consists of several steps with each step setting certain state and passing the data over to the next step.</p>

<p>Test scenario:</p>

<pre><code>1. Create item.
2. Assign item to group.
3. Approve item.
...
4. Publish item.
</code></pre>

<p>The steps are not atomic and depend on each other. The test class extends from <code>unittest.TestCase</code> and contains a single <code>test_xyz()</code> method which wraps the methods for each step.</p>

<p>Currently, the final report only includes the pass/fail status for the wrapper <code>test_xyz()</code> method. I would like to have each step being treated as a 'test step' and have a separate entry in the test report.</p>

<p>It feels wrong to convert all the steps into <code>test_step1()</code>, <code>test_step2()</code> etc and then enforcing the execution order and data exchange since the steps are not self-contained tests.</p>

<p>Is there a way to mark certain methods as test steps so that they appear as separate entries in the test report? </p>

<p>Basically, all I want is improving the visual reporting so that it is more obvious from the report at which step the entire integration test failed. Is this achievable with <code>unittest</code>? What would be the best practice in organizing the code so that it fits into the unittest paradigm?</p>

<p>Not sure <code>unittest</code> is the best tool for integration tests, since this is not strictly speaking <em>unit testing</em>. Would switching to something like pytest make more sense for integration testing while still allowing 'free' HTML report generation? (I am currently using <a href=""http://nose.readthedocs.io/"" rel=""noreferrer"">nose</a> to run the test and to generate the HTML report with the corresponding <a href=""https://pypi.python.org/pypi/nose-html-reporting"" rel=""noreferrer"">nose plugin</a>.)</p>
",https://stackoverflow.com/questions/44750839/integration-testing-with-python-unittest-how-to-improve-granularity,"['python', 'integration-testing', 'pytest', 'python-unittest', 'nose']",8665,TRUE,6,1
Transactional Integration Testing ASP.Net Core and Entity Framework Core,"<p>I’m curious if anyone has gone down the road of <strong>transactional integration testing with aspnet and ef core</strong>? I want to be able to perform full integration tests all the way to the db (not using an in-memory db). There are 2 problems:</p>

<ul>
<li>Tests can have side effects, but should be run in isolation since side effects could cause other tests to fail. I don’t want the devs to be required to write excessive cleanup code after each test. </li>
<li>I can teardown and recreate the db every test run but as the test counts start reaching the 100s it becomes unbearably slow to run the tests.</li>
</ul>

<p>I would like to wrap tests in a transaction (<code>_dbContext.Database.BeginTransactionAsync()</code>). The problem is the DbContext I get from:</p>

<pre><code>_server = new TestServer(builder);
_services = _server.Host.Services;
_dbContext = (AppDbContext)_services.GetService(typeof(AppDbContext))
</code></pre>

<p>Will be in a different scope (so a different instance) than the one that gets resolved by the AspNetCore middleware. So, only the test code would be transactional, not any code executed by the <code>TestServer</code>. I have considered using some test middleware in a <code>TestStartup</code> class that would wrap the API code in a transaction, but the problem there is it will be disposed/rolled back before the test can evaluate it. Consider the following use case:</p>

<ul>
<li>send POST to create resource</li>
<li>assert the dbContext contains the resource</li>
</ul>

<p>In this case, the test needs access to the <em>same</em> dbContext instance used by the test server. 
I tried a few hacky ways of passing the context using <code>AsyncLocal</code> which didn’t work so then I just tried using a simple <code>static</code> member. <strike>But, that also didn’t work, so it appears there is some AppDomain isolation between the test app and the <code>TestServer</code>.</strike>
I’m curious if anyone has gone down this road and if so, what they came up with?</p>
",https://stackoverflow.com/questions/47740479/transactional-integration-testing-asp-net-core-and-entity-framework-core,"['c#', 'asp.net', 'asp.net-core', '.net-core', 'entity-framework-core']",1839,TRUE,3,1
Scope of Integration Testing in a CI CD workflow,"<p>The question is more about the fundamental understanding of a normal/ideal CI flow and understanding the scope of integration testing in it.</p>

<p>As per my understanding, the basic CI CD flow is</p>

<pre><code>UnitTesting --&gt; IntegrationTesting --&gt; Build Artifact --&gt; Deploy to Dev/Sandbox or any other subsequent environments.
</code></pre>

<p>So unit tetsing and integration testing collectively decide/make sure if the build is stable and ready to be deployed.</p>

<p>But, recently, we had this discussion in my team where we wanted to run integration tests on deployed instances on Dev/Sandbox etc , so as to verify if the application is working fine after deployment.</p>

<p>And the <a href=""https://msdn.microsoft.com/en-us/library/hh191495.aspx"" rel=""nofollow noreferrer"">microsoft's article</a> on Build - Deploy - Test workflows suggests that this could be a possible way. </p>

<p>So , my questions are :-</p>

<ol>
<li>Are integration tests supposed to test configuration of different environments ?</li>
<li>Are integration tests supposed to be run before packaging application or deploying the application ?</li>
<li>If at all, some automated testing is required to test deployed application functioning on all environments ?
If not integration tests then what could be alternative solutions</li>
</ol>
",https://stackoverflow.com/questions/44282209/scope-of-integration-testing-in-a-ci-cd-workflow,"['web-services', 'continuous-integration', 'tdd', 'integration-testing', 'continuous-deployment']",226,TRUE,2,1
integration testing with glassfish embedded - exception : expected stackmap frame,"<p>I had an assignment of writing <code>unit tests</code>, which gradually became writing <code>integration tests</code>. I'm rather new with <code>embedded glassfish server</code>. I'll try to explain my problem as best as I can, please bear with me.</p>

<p>This is my relevant <code>pom.xml</code> part:</p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.glassfish.main.extras&lt;/groupId&gt;
    &lt;artifactId&gt;glassfish-embedded-all&lt;/artifactId&gt;
    &lt;version&gt;4.1.2&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;junit&lt;/groupId&gt;
    &lt;artifactId&gt;junit&lt;/artifactId&gt;
    &lt;version&gt;4.11&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
    &lt;type&gt;jar&lt;/type&gt;
&lt;/dependency&gt;
</code></pre>

<p>This is my relevant TestClass(EmbeddedContainerFirstTest) code:</p>

<pre><code>public class EmbeddedContainerFirstTest extends TestCase {

     private Context  ctx;
     private EJBContainer ejbContainer;

    @BeforeClass
    public  void setUp() {
        // below line is where exception is thrown. 
        // so my ejb beans can not be deployed successfully to glassfish embedded server
        ejbContainer = EJBContainer.createEJBContainer();
        System.out.println(""Opening the container"" );
        ctx = ejbContainer.getContext();
    }

    @AfterClass
    public  void tearDown() {
        ejbContainer.close();
        System.out.println(""Closing the container"" );
    }
}
</code></pre>

<p>Imagine an <code>ear</code> file, in which there are <code>jars</code> from more than 5 companies. We deploy that file to <code>WildFly 10.0</code>. I have found <a href=""https://stackoverflow.com/questions/6469751/testing-an-ejb-with-junit/20635285#20635285"">this post</a> on stackoverflow about writing tests for <code>Java EE applications</code>. When I try this on a simple module it works, but when I try it on a module with dependencies from other companies it fails. It fails with:</p>

<pre><code>Exception Details:
  Location:
    com/milsoft/turkuaz/core/comm/dds/TurkuazAbstractDDSEntityCommunicator.newData(Ljava/lang/String;Lcom/milsoft/turkuaz/core/comm/TurkuazMessage;)V @28: ifeq
  Reason:
    Expected stackmap frame at this location.
  Bytecode:
    0x0000000: 2cb9 0022 0100 4e2a b400 142d 03b9 0024
    0x0000010: 0300 3a04 b200 13b9 002a 0100 9900 35b2
    0x0000020: 0013 bb00 1059 b700 192a b600 18b6 001a
    0x0000030: 1203 b600 1b2a b400 15b6 0018 b600 1a12
    0x0000040: 01b6 001b 1904 b600 1ab6 001c b900 2802
    0x0000050: 002a b400 1519 04b9 0026 0200 b1

        at java.lang.Class.getDeclaredConstructors0(Native Method)
        at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
        at java.lang.Class.getConstructors(Class.java:1651)
        at org.glassfish.apf.impl.ComponentDefinition.initializeConstructors(ComponentDefinition.java:116)
        at org.glassfish.apf.impl.ComponentDefinition.&lt;init&gt;(ComponentDefinition.java:74)
        at org.glassfish.apf.impl.JavaEEScanner.getComponentInfo(JavaEEScanner.java:70)
        at org.glassfish.apf.impl.AnnotationProcessorImpl.process(AnnotationProcessorImpl.java:177)
        at org.glassfish.apf.impl.AnnotationProcessorImpl.process(AnnotationProcessorImpl.java:134)
        at com.sun.enterprise.deployment.archivist.Archivist.processAnnotations(Archivist.java:627)
        at com.sun.enterprise.deployment.archivist.Archivist.readAnnotations(Archivist.java:463)
        at com.sun.enterprise.deployment.archivist.Archivist.readAnnotations(Archivist.java:447)
        at com.sun.enterprise.deployment.archivist.Archivist.readRestDeploymentDescriptors(Archivist.java:419)
        at com.sun.enterprise.deployment.archivist.Archivist.readDeploymentDescriptors(Archivist.java:396)
        at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:271)
        at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:280)
        at com.sun.enterprise.deployment.archivist.ApplicationArchivist.readModulesDescriptors(ApplicationArchivist.java:611)
        at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openWith(ApplicationArchivist.java:229)
        at com.sun.enterprise.deployment.archivist.ApplicationFactory.openWith(ApplicationFactory.java:232)
        at org.glassfish.javaee.core.deployment.DolProvider.processDOL(DolProvider.java:193)
        at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:227)
        at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:96)
        at com.sun.enterprise.v3.server.ApplicationLifecycle.loadDeployer(ApplicationLifecycle.java:881)
        at com.sun.enterprise.v3.server.ApplicationLifecycle.setupContainerInfos(ApplicationLifecycle.java:821)
        at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:377)
        at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
        at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:360)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:360)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
        at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:133)
        at org.glassfish.ejb.embedded.EJBContainerImpl.deploy(EJBContainerImpl.java:141)
        at org.glassfish.ejb.embedded.EJBContainerProviderImpl.createEJBContainer(EJBContainerProviderImpl.java:134)
        at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:127)
        at EmbeddedContainerFirstTest.setUp(EmbeddedContainerFirstTest.java:26)
        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:47)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
        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.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

Haz 21, 2017 10:43:40 AM org.glassfish.deployment.admin.DeployCommand execute
SEVERE: Exception while deploying the app [ejb-app] : Expecting a stackmap frame at branch target 81
Exception Details:
  Location:
    com/milsoft/turkuaz/core/comm/dds/TurkuazAbstractDDSEntityCommunicator.newData(Ljava/lang/String;Lcom/milsoft/turkuaz/core/comm/TurkuazMessage;)V @28: ifeq
  Reason:
    Expected stackmap frame at this location.
  Bytecode:
    0x0000000: 2cb9 0022 0100 4e2a b400 142d 03b9 0024
    0x0000010: 0300 3a04 b200 13b9 002a 0100 9900 35b2
    0x0000020: 0013 bb00 1059 b700 192a b600 18b6 001a
    0x0000030: 1203 b600 1b2a b400 15b6 0018 b600 1a12
    0x0000040: 01b6 001b 1904 b600 1ab6 001c b900 2802
    0x0000050: 002a b400 1519 04b9 0026 0200 b1

Haz 21, 2017 10:43:40 AM org.glassfish.ejb.embedded.EJBContainerProviderImpl createEJBContainer
INFO: [EJBContainerProviderImpl] Cleaning up on failure ...
Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 37.581 sec &lt;&lt;&lt; FAILURE!
testApp(EmbeddedContainerFirstTest)  Time elapsed: 37.537 sec  &lt;&lt;&lt; ERROR!
javax.ejb.EJBException: Failed to deploy EJB modules - see log for details
        at org.glassfish.ejb.embedded.EJBContainerImpl.deploy(EJBContainerImpl.java:149)
        at org.glassfish.ejb.embedded.EJBContainerProviderImpl.createEJBContainer(EJBContainerProviderImpl.java:134)
        at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:127)
        at EmbeddedContainerFirstTest.setUp(EmbeddedContainerFirstTest.java:26)
        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:47)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
        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.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
</code></pre>

<p>Below is <code>project view</code>, in the <code>editor panel of Idea line 95</code> is where exception is thrown. It is also my <code>Singleton bean</code>. <code>TurkuazMessage</code> class is from another companies <code>jar</code>, where I don't have access to the <code>source code</code> of that <code>jar</code>:</p>

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

<p>This failure is due to some <code>jars</code> compiled with <code>different java versions</code>. In <code>my server run configuration</code> I solved it adding <code>-noverify</code> into <code>VM options</code>. If I remove <code>-noverify</code> from <code>my server run conf. vm options</code> I get the <code>same exception</code> above. So, I also needed to <code>run embedded glassfish with -noverify</code>. To do that I added my <code>custom domain.xml</code> into <code>test sources</code> of my module in <code>Idea</code>. The only difference between <code>my domain.xml and default domain.xml</code> is <code>jvm options</code>. This is my <code>domain.xml</code>:</p>

<pre><code>&lt;domain log-root=""${com.sun.aas.instanceRoot}/logs"" application-root=""${com.sun.aas.instanceRoot}/applications"" version=""10.0""&gt;
    &lt;security-configurations&gt;
        &lt;authorization-service default=""true"" name=""authorizationService""&gt;
            &lt;security-provider name=""simpleAuthorization"" type=""Simple"" provider-name=""simpleAuthorizationProvider""&gt;
                &lt;authorization-provider-config support-policy-deploy=""false"" name=""simpleAuthorizationProviderConfig""&gt;&lt;/authorization-provider-config&gt;
            &lt;/security-provider&gt;
        &lt;/authorization-service&gt;
    &lt;/security-configurations&gt;
    &lt;system-applications /&gt;
    &lt;applications /&gt;
    &lt;resources&gt;
        &lt;jdbc-resource pool-name=""__TimerPool"" jndi-name=""jdbc/__TimerPool"" object-type=""system-admin"" /&gt;
        &lt;jdbc-resource pool-name=""DerbyPool"" jndi-name=""jdbc/__default"" object-type=""system-all"" /&gt;
        &lt;jdbc-connection-pool name=""__TimerPool"" datasource-classname=""org.apache.derby.jdbc.EmbeddedXADataSource"" res-type=""javax.sql.XADataSource""&gt;
            &lt;property value=""${com.sun.aas.instanceRoot}/lib/databases/ejbtimer"" name=""databaseName"" /&gt;
            &lt;property value="";create=true"" name=""connectionAttributes"" /&gt;
        &lt;/jdbc-connection-pool&gt;
        &lt;jdbc-connection-pool is-isolation-level-guaranteed=""false"" name=""DerbyPool"" datasource-classname=""org.apache.derby.jdbc.EmbeddedDataSource"" res-type=""javax.sql.DataSource""&gt;
            &lt;property name=""databaseName"" value=""${com.sun.aas.instanceRoot}/lib/databases/embedded_default"" /&gt;
            &lt;property name=""connectionAttributes"" value="";create=true"" /&gt;
        &lt;/jdbc-connection-pool&gt;
    &lt;/resources&gt;
    &lt;servers&gt;
        &lt;server name=""server"" config-ref=""server-config""&gt;
            &lt;resource-ref ref=""jdbc/__TimerPool"" /&gt;
            &lt;resource-ref ref=""jdbc/__default"" /&gt;
        &lt;/server&gt;
    &lt;/servers&gt;
    &lt;configs&gt;
        &lt;config name=""server-config""&gt;
            &lt;http-service&gt;
                &lt;access-log rotation-interval-in-minutes=""15"" rotation-suffix=""yyyy-MM-dd"" /&gt;
                &lt;virtual-server id=""server"" network-listeners=""http-listener, https-listener"" /&gt;
            &lt;/http-service&gt;
            &lt;iiop-service&gt;
                &lt;orb use-thread-pool-ids=""thread-pool-1"" /&gt;
                &lt;iiop-listener address=""0.0.0.0"" port=""3700"" id=""orb-listener-1"" /&gt;
                &lt;iiop-listener security-enabled=""true"" address=""0.0.0.0"" port=""3820"" id=""SSL""&gt;
                    &lt;ssl classname=""com.sun.enterprise.security.ssl.GlassfishSSLImpl"" cert-nickname=""s1as"" /&gt;
                &lt;/iiop-listener&gt;
                &lt;iiop-listener security-enabled=""true"" address=""0.0.0.0"" port=""3920"" id=""SSL_MUTUALAUTH""&gt;
                    &lt;ssl classname=""com.sun.enterprise.security.ssl.GlassfishSSLImpl"" cert-nickname=""s1as"" client-auth-enabled=""true"" /&gt;
                &lt;/iiop-listener&gt;
            &lt;/iiop-service&gt;
            &lt;admin-service type=""das-and-server"" system-jmx-connector-name=""system""&gt;
                &lt;jmx-connector enabled=""false"" auth-realm-name=""admin-realm"" security-enabled=""false"" address=""0.0.0.0"" port=""8686"" name=""system"" /&gt;
                &lt;das-config autodeploy-enabled=""false"" dynamic-reload-enabled=""true"" deploy-xml-validation=""full"" autodeploy-dir=""${com.sun.aas.instanceRoot}/autodeploy"" /&gt;
                &lt;property value=""/admin"" name=""adminConsoleContextRoot"" /&gt;
                &lt;property value=""${com.sun.aas.installRoot}/lib/install/applications/admingui.war"" name=""adminConsoleDownloadLocation"" /&gt;
                &lt;property value=""${com.sun.aas.installRoot}/.."" name=""ipsRoot"" /&gt;
            &lt;/admin-service&gt;
            &lt;connector-service shutdown-timeout-in-seconds=""30""&gt;
            &lt;/connector-service&gt;
            &lt;ejb-container steady-pool-size=""0"" max-pool-size=""32"" session-store=""${com.sun.aas.instanceRoot}/session-store"" pool-resize-quantity=""8""&gt;
                &lt;ejb-timer-service /&gt;
            &lt;/ejb-container&gt;
            &lt;mdb-container steady-pool-size=""0"" max-pool-size=""32"" pool-resize-quantity=""8"" &gt;
            &lt;/mdb-container&gt;
            &lt;jms-service type=""EMBEDDED"" default-jms-host=""default_JMS_host""&gt;
                &lt;jms-host name=""default_JMS_host"" host=""localhost"" port=""7676"" admin-user-name=""admin"" admin-password=""admin"" lazy-init=""false""/&gt;
            &lt;/jms-service&gt;
            &lt;log-service file=""${com.sun.aas.instanceRoot}/logs/server.log"" log-rotation-limit-in-bytes=""2000000""&gt;
                &lt;module-log-levels /&gt;
            &lt;/log-service&gt;
            &lt;security-service activate-default-principal-to-role-mapping=""true"" jacc=""simple""&gt;
                &lt;auth-realm classname=""com.sun.enterprise.security.auth.realm.file.FileRealm"" name=""admin-realm""&gt;
                    &lt;property value=""${com.sun.aas.instanceRoot}/config/admin-keyfile"" name=""file"" /&gt;
                    &lt;property value=""fileRealm"" name=""jaas-context"" /&gt;
                &lt;/auth-realm&gt;
                &lt;auth-realm classname=""com.sun.enterprise.security.auth.realm.file.FileRealm"" name=""file""&gt;
                    &lt;property value=""${com.sun.aas.instanceRoot}/config/keyfile"" name=""file"" /&gt;
                    &lt;property value=""fileRealm"" name=""jaas-context"" /&gt;
                &lt;/auth-realm&gt;
                &lt;auth-realm classname=""com.sun.enterprise.security.auth.realm.certificate.CertificateRealm"" name=""certificate"" /&gt;
                &lt;jacc-provider policy-configuration-factory-provider=""com.sun.enterprise.security.provider.PolicyConfigurationFactoryImpl"" policy-provider=""com.sun.enterprise.security.provider.PolicyWrapper"" name=""default""&gt;
                    &lt;property value=""${com.sun.aas.instanceRoot}/generated/policy"" name=""repository"" /&gt;
                &lt;/jacc-provider&gt;
                &lt;jacc-provider policy-configuration-factory-provider=""com.sun.enterprise.security.jacc.provider.SimplePolicyConfigurationFactory"" policy-provider=""com.sun.enterprise.security.jacc.provider.SimplePolicyProvider"" name=""simple"" /&gt;
                &lt;audit-module classname=""com.sun.enterprise.security.ee.Audit"" name=""default""&gt;
                    &lt;property value=""false"" name=""auditOn"" /&gt;
                &lt;/audit-module&gt;
                &lt;message-security-config auth-layer=""SOAP""&gt;
                    &lt;provider-config provider-id=""XWS_ClientProvider"" class-name=""com.sun.xml.wss.provider.ClientSecurityAuthModule"" provider-type=""client""&gt;
                        &lt;request-policy auth-source=""content"" /&gt;
                        &lt;response-policy auth-source=""content"" /&gt;
                        &lt;property value=""s1as"" name=""encryption.key.alias"" /&gt;
                        &lt;property value=""s1as"" name=""signature.key.alias"" /&gt;
                        &lt;property value=""false"" name=""dynamic.username.password"" /&gt;
                        &lt;property value=""false"" name=""debug"" /&gt;
                    &lt;/provider-config&gt;
                    &lt;provider-config provider-id=""ClientProvider"" class-name=""com.sun.xml.wss.provider.ClientSecurityAuthModule"" provider-type=""client""&gt;
                        &lt;request-policy auth-source=""content"" /&gt;
                        &lt;response-policy auth-source=""content"" /&gt;
                        &lt;property value=""s1as"" name=""encryption.key.alias"" /&gt;
                        &lt;property value=""s1as"" name=""signature.key.alias"" /&gt;
                        &lt;property value=""false"" name=""dynamic.username.password"" /&gt;
                        &lt;property value=""false"" name=""debug"" /&gt;
                        &lt;property value=""${com.sun.aas.instanceRoot}/config/wss-server-config-1.0.xml"" name=""security.config"" /&gt;
                    &lt;/provider-config&gt;
                    &lt;provider-config provider-id=""XWS_ServerProvider"" class-name=""com.sun.xml.wss.provider.ServerSecurityAuthModule"" provider-type=""server""&gt;
                        &lt;request-policy auth-source=""content"" /&gt;
                        &lt;response-policy auth-source=""content"" /&gt;
                        &lt;property value=""s1as"" name=""encryption.key.alias"" /&gt;
                        &lt;property value=""s1as"" name=""signature.key.alias"" /&gt;
                        &lt;property value=""false"" name=""debug"" /&gt;
                    &lt;/provider-config&gt;
                    &lt;provider-config provider-id=""ServerProvider"" class-name=""com.sun.xml.wss.provider.ServerSecurityAuthModule"" provider-type=""server""&gt;
                        &lt;request-policy auth-source=""content"" /&gt;
                        &lt;response-policy auth-source=""content"" /&gt;
                        &lt;property value=""s1as"" name=""encryption.key.alias"" /&gt;
                        &lt;property value=""s1as"" name=""signature.key.alias"" /&gt;
                        &lt;property value=""false"" name=""debug"" /&gt;
                        &lt;property value=""${com.sun.aas.instanceRoot}/config/wss-server-config-1.0.xml"" name=""security.config"" /&gt;
                    &lt;/provider-config&gt;
                &lt;/message-security-config&gt;
                &lt;property value=""SHA-256"" name=""default-digest-algorithm"" /&gt;
            &lt;/security-service&gt;
            &lt;monitoring-service&gt;
                &lt;module-monitoring-levels /&gt;
            &lt;/monitoring-service&gt;
            &lt;transaction-service tx-log-dir=""${com.sun.aas.instanceRoot}/logs"" &gt;
            &lt;/transaction-service&gt;
            &lt;java-config&gt;
                &lt;!--&lt;jvm-options&gt;-Djavax.net.ssl.keyStore=${com.sun.aas.instanceRoot}/config/keystore.jks&lt;/jvm-options&gt;--&gt;
                &lt;!--&lt;jvm-options&gt;-Djavax.net.ssl.trustStore=${com.sun.aas.instanceRoot}/config/cacerts.jks&lt;/jvm-options&gt;--&gt;
                &lt;!--&lt;jvm-options&gt;-Dorg.glassfish.jms.InitializeOnDemand=true&lt;/jvm-options&gt;--&gt;
                &lt;jvm-options&gt;-Xms64m&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-Xmx512m&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-XX:+UseConcMarkSweepGC&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-Dorg.jboss.resolver.warning=true&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-Djava.net.preferIPv4Stack=true&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-Dsun.rmi.dgc.client.gcInterval=3600000&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-Dsun.rmi.dgc.server.gcInterval=3600000&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-Djboss.modules.system.pkgs=org.jboss.byteman&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-Djava.awt.headless=true&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-noverify&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl&lt;/jvm-options&gt;
                &lt;jvm-options&gt;-Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl&lt;/jvm-options&gt;
            &lt;/java-config&gt;
            &lt;network-config&gt;
                &lt;protocols&gt;
                    &lt;protocol name=""http-listener""&gt;
                        &lt;http default-virtual-server=""server"" max-connections=""250""&gt;
                            &lt;file-cache enabled=""false""&gt;&lt;/file-cache&gt;
                        &lt;/http&gt;
                    &lt;/protocol&gt;
                    &lt;protocol security-enabled=""true"" name=""https-listener""&gt;
                        &lt;http default-virtual-server=""server"" max-connections=""250""&gt;
                            &lt;file-cache enabled=""false""&gt;&lt;/file-cache&gt;
                        &lt;/http&gt;
                        &lt;ssl classname=""com.sun.enterprise.security.ssl.GlassfishSSLImpl"" ssl3-enabled=""false"" cert-nickname=""s1as""&gt;&lt;/ssl&gt;
                    &lt;/protocol&gt;
                &lt;/protocols&gt;
                &lt;network-listeners&gt;
                    &lt;network-listener port=""0"" protocol=""http-listener"" transport=""tcp"" name=""http-listener"" thread-pool=""http-thread-pool"" enabled=""false"" /&gt;
                    &lt;network-listener port=""0"" protocol=""https-listener"" transport=""tcp"" name=""https-listener"" thread-pool=""http-thread-pool"" enabled=""false"" /&gt;
                &lt;/network-listeners&gt;
                &lt;transports&gt;
                    &lt;transport name=""tcp""&gt;&lt;/transport&gt;
                &lt;/transports&gt;
            &lt;/network-config&gt;
            &lt;thread-pools&gt;
                &lt;thread-pool name=""http-thread-pool"" max-queue-size=""4096""&gt;&lt;/thread-pool&gt;
                &lt;thread-pool name=""thread-pool-1"" max-thread-pool-size=""200""/&gt;
            &lt;/thread-pools&gt;
        &lt;/config&gt;
    &lt;/configs&gt;
    &lt;property name=""administrative.domain.name"" value=""domain1""/&gt;
&lt;/domain&gt;
</code></pre>

<p>Using above <code>domain.xml</code> did not solve my problem. What can I do to solve this problem? If you need any more info I'll try to add as soon as I can.  I am open to any ideas. Thanks in advance.</p>
",https://stackoverflow.com/questions/44677634/integration-testing-with-glassfish-embedded-exception-expected-stackmap-fram,"['java', 'jakarta-ee', 'jvm', 'integration-testing', 'glassfish-embedded']",401,FALSE,2,0
How to use the actual database for integration testing?,"<p>There were some proposed solutions to the question ""How to test SQL statements in an application"" -</p>

<ul>
<li>Using RAM memory - I can't change the configuration of staging environment where testing happens.</li>
<li>Using H2 - Not very compatible even in PostgreSQL mode</li>
<li>Use the same database to run the tests.</li>
<li>Using in-memory mode - PostgreSQL doesn't have one.</li>
</ul>

<p>The third one was viable and I looked into <a href=""https://www.testcontainers.org/"" rel=""nofollow noreferrer"">Test Containers</a> which is actually a beautiful solution but a relatively new one. As a result, our company is sceptical of adopting it.</p>

<p>We use <code>Mybatis</code> to access <code>PostgreSQL</code>. </p>

<p>Another way would be to recreate entire schema and populate required tables before tests. Here is the problem, I could create and delete schema with tables with the same name. To avoid name collision I'd have to change schema's name, as a result, even queries should be renamed which is not at all preferred. Is there a way to do this without changing queries but pointing them to the dummy schema.</p>
",https://stackoverflow.com/questions/43586169/how-to-use-the-actual-database-for-integration-testing,"['java', 'postgresql', 'integration-testing']",6061,TRUE,2,2
Unit/integration testing EF with Effort - Connectionstring not found,"<p>I recently started using the in-memory database Effort to unit test my entity framework implementations.</p>

<p>Everything works well, except when I try to load data from a CSV file into the database using the CSV dataloader.</p>

<p>Documentation on exactly how to configure the csvdataloader seems to be scarce / insufficient.</p>

<p>Here is one of the NUnit 3.0 unit tests I have written:</p>

<pre><code>    [Test]
    public void GetBudgetIncomeItems_MultipleValidItems_ReturnList()
    {
        //Prepare and load data
        var dataLoader = new CsvDataLoader(@""&lt;DirectoryOfUnitTestProject&gt;\Data"");
        var entityConnection = Effort.EntityConnectionFactory.CreateTransient(""name=&lt;NameOfMyCSVFileWithoutCSVExtension/DatabaseName&gt;"", dataLoader);
        _serviceContext = new ServiceContext(entityConnection);

        //Execute test
        var items = _query.GetBudgetIncomeItems(new Application {Id = 3});

        //Check results
        //Some assertions
    }
</code></pre>

<p>An exception is thrown on the line:</p>

<pre><code>Effort.EntityConnectionFactory.CreateTransient(""name=&lt;NameOfMyCSVFileWithoutCSVExtension/DatabaseName&gt;"", dataLoader);
</code></pre>

<p>Exception detail:</p>

<blockquote>
  <p>System.ArgumentException was unhandled by user code<br>
  HResult=-2147024809   Message=Connectionstring was not found Parameter
  name: entityConnectionString   ParamName=entityConnectionString<br>
  Source=Effort   StackTrace:
         at Effort.EntityConnectionFactory.GetFullEntityConnectionString(String
  entityConnectionString)
         at Effort.EntityConnectionFactory.GetEffortCompatibleMetadataWorkspace(String&amp;
  entityConnectionString)
         at Effort.EntityConnectionFactory.CreateTransient(String entityConnectionString, IDataLoader dataLoader)
         at Infrastructure.EF6.UnitTests.PacsQueryTests`1.GetBudgetIncomeItems_MultipleValidItems_ReturnList()
  in
  \PacsQueryTests.cs:line
  36   InnerException:</p>
</blockquote>

<p>Any help would be appreciated...</p>

<h2>Update</h2>

<p>As per comments from @Evk below, when using Code first, you have to make use of the DbConnection and DbConnectionFactory classes, and not the EntityConnection and EntityConnectionFactory classes.</p>

<p>My updated code, which does not throw any errors, looks as follows:</p>

<pre><code>        [Test]
        public void GetBudgetIncomeItems_MultipleValidItems_ReturnList()
        {
            //Prepare and load data
            Effort.DataLoaders.IDataLoader csvDataLoader = new Effort.DataLoaders.CsvDataLoader(@""&lt;DirectoryOfUnitTestProject&gt;\Data"");
            var dataLoader = new Effort.DataLoaders.CachingDataLoader(csvDataLoader,false);
            DbConnection dbConnection = Effort.DbConnectionFactory.CreateTransient(dataLoader);
            _serviceContext = new ServiceContext(dbConnection);

            //Execute test
            var items = _query.GetBudgetIncomeItems(new Application {Id = 3});

            //Check results
            //Some assertions
        }
</code></pre>
",https://stackoverflow.com/questions/42827244/unit-integration-testing-ef-with-effort-connectionstring-not-found,"['c#', 'entity-framework', 'unit-testing', 'effort']",1670,FALSE,2,1
Integration testing a DynamoDB client which uses inconsistent reads?,"<p>Situation:</p>

<ol>
<li>A <strong>web service</strong> with an API to read records from DynamoDB. It uses eventually consistent reads (<code>GetItem</code> default mode)</li>
<li>An <strong>integration test</strong> consisting of two steps:

<ul>
<li>create test data in DynamoDB</li>
<li>call the service to verify that it is returning the expected result</li>
</ul></li>
</ol>

<p>I worry that this test is bound to be fragile due to eventual consistency of the data.</p>

<p>If I attempt to verify the data immediately after writing using <code>GetItem</code> <code>withConsistenRead=true</code> it only guarantees that the data has been written to the <em>majority of DB copies</em>, but not all, so the service under test still has a chance to read from the non-updated copy on the next step.</p>

<p>Is there a way to ensure that the data has been written to <strong>all</strong> DynamoDB copies before proceeding?</p>
",https://stackoverflow.com/questions/42152194/integration-testing-a-dynamodb-client-which-uses-inconsistent-reads,"['amazon-dynamodb', 'eventual-consistency']",952,TRUE,1,1
Integration Testing Java application with C++ unit testing framework,"<p>I have a Client/Server application written in Java (client) and C++ (server).</p>

<p>I was wondering if there was a way of using Gtest (or any other testing framework, not necessarily in C++, as long as it's not a Java framework) as a base framework to perform tests on the Java side.</p>

<p>So basically, what I want to achieve is in the following <strong>pseudo-code</strong>:</p>

<pre><code>// inside MyClass.java

public class MyClass{
    public int myMethod(){
        return 42;
    }
}

//-------------------\\
// inside MyTest.cpp \\

TEST_F(MyJavaClassTest, meaning_of_life)
{
    ASSERT_EQUALS(MyClass.myMethod(), 42);
}

//--------\\
// Output \\

[ RUN      ] MyJavaClassTest.meaning_of_life
[       OK ] MyJavaClassTest.meaning_of_life (0 ms)
</code></pre>
",https://stackoverflow.com/questions/44778646/integration-testing-java-application-with-c-unit-testing-framework,"['java', 'c++', 'unit-testing']",217,TRUE,0,1
Integration testing (preferably TravisCI) in a Gentoo Linux enviornment,"<p>I would like to benefit from the excellent package management capabilities and neuro/scientific support of Gentoo Linux when I am setting up continuous integration (CI) testing for my software (e.g. <a href=""https://github.com/IBT-FMI/SAMRI"" rel=""nofollow noreferrer"">SAMRI</a>).</p>

<p>Sadly, my favorite platform, TravisCI, seems to offer Ubuntu, Ubuntu, and MacOS environments only. I would like to know how to best (i.e. with minimal overhead and delay) set up a Gentoo Linux environment on TravisCI (or if need be, on another CI platform).</p>

<p>I have tried using the <a href=""https://wiki.gentoo.org/wiki/Project:Prefix"" rel=""nofollow noreferrer"">Gentoo Prefix</a> bootstrap script, however:</p>

<ul>
<li>simply calling it in <code>- yes """" | ./bootstrap-prefix.ch</code> will overflow the 4MB log limit</li>
<li>redirecting it to a file <code>- yes """" | ./bootstrap-prefix.sh &gt;&gt; prefix_log.txt</code> will cause the job to time out</li>
<li>I can't figure out how to increase the time out for such a command. <code>-
travis_wait 60 |&amp; yes """" | ./bootstrap-prefix.sh &gt;&gt; prefix_log.txt</code> times out after 10 minutes.</li>
</ul>

<p>In excess of all these issues, I feel bootstrapping an entire Gentoo install from scratch is a waste of time and resources. I am thinking maybe this can be more elegantly addressed by using one of the <a href=""https://wiki.gentoo.org/wiki/Project:Openstack"" rel=""nofollow noreferrer"">Gentoo OpenStack</a> images - or something else?</p>
",https://stackoverflow.com/questions/45571455/integration-testing-preferably-travisci-in-a-gentoo-linux-enviornment,"['operating-system', 'continuous-integration', 'integration-testing', 'travis-ci', 'gentoo']",73,FALSE,0,1
why doesnt service method rollback when doing integration testing?,"<p>I want to include only relevant code.</p>

<pre><code>void testSaveQuestion_WrongRaceId(){
    ...
controller.savequestion(raceGroup.id)
    ...
}
</code></pre>

<p>The save question controller uses service method which is transactional by default. The call to service method is shown below. </p>

<pre><code>  def savequestion(Long id){


            try {

                surveyService.saveQuestion(id, params, question, event)

            }
            catch (ValidationException e) {
}

    }
</code></pre>

<p>If i set    </p>

<pre><code>static transactional = false
</code></pre>

<p>then it works. i.e if an exception is thrown in service method then it rollsback. </p>

<p>but if i comment out </p>

<pre><code>//static transactional = false
</code></pre>

<p>then it fails. i.e if an exception is thrown in service method then it doesnt roll back. </p>

<p>I check this rolling back behavior by asserting the entries in the database. For example if there is an exception then a question is not supposed to be saved in database but if there is not an exception then the count of question is 1. </p>

<p>So i am wondering why is service method not rolling back after an exception is thrown when doing integration testing? Why does it work only after making transactional = false in integration testing class. Please note i am using grails 2.2</p>

<p>I appreciate any help!</p>
",https://stackoverflow.com/questions/47767260/why-doesnt-service-method-rollback-when-doing-integration-testing,"['grails', 'integration-testing', 'grails-2.2']",47,FALSE,0,0
C#.NET Bamboo and Regression/Integration Testing Architecture w/Selenium,"<p>This is broad in scope, so I hope I can narrow it down to a concise set of questions. I basically need to know the technologies required to setup a Continuous Integration Testing/Deployment per Bamboo in C#.</p>

<p>Our Architecture is currently:</p>

<ul>
<li>Product: C#.NET/WCF -> Commit -> Build(Bamboo) -> Manually deploy to QA Server(AWS)<br/>
Product is a multi-service architecture.</li>
<li><p>Testing: C#/Selenium/NUnit -> Run tests manually<br/>
Testing solution is it's own repo setup with:</p>

<ol>
<li>Class Library Project (Page Object Model) </li>
<li>Test Project with all of our Integration tests.</li>
</ol></li>
<li><p>Team Communication: Agile with JIRA.</p></li>
<li><b>EDIT:</b> this is all cloud based.</li>
</ul>

<hr>

<p>I need to adapt this into a Continuous Integration System: </p>

<ul>
<li>Product: Commit -> Build -> Deploy to Testing Server.</li>
<li>Testing Solution: (If there's new commits then Commit -> Build) Run against Testing Server

<ol>
<li>If Pass -> Deploy Product to QA server</li>
<li>If fail -> create JIRA issue, notify developer.</li>
</ol></li>
</ul>

<hr>

<p>Once I am at Bamboo, I have many plugins at my disposal... BUT, there are so many high level tutorials, videos, etc that talk about Jenkins, maven, Cucumber, etc, etc... I have no clue which setup will handle our architecture. And, are compatible with C#.NET, Selenium, etc.</p>

<ul>
<li>What plugin(tool) can auto-deploy a multi-service architecture in c#.net/wcf?</li>
<li>What plugin works with our testing framework: C#.NET w/Selenium and NUnit?</li>
<li>What plugin(s) can run our testing framework AFTER the product has been deployed to the testing server? We are required to have at least parts of the multi-service architecture running to preform tests.</li>
<li>How do I utilize my Testing Framework in this architecture? Can it even be ran from Bamboo when a developer commits? And how do I tie this into the system to successfully re-deploy to another server if pass, or create an issue and send it back to the developer if fail.</li>
</ul>

<p>What technology route do I need to take to accomplish this?</p>

<p>So far I have:
Bamboo, Maven, Cucumber to execute testing framework against the Testing server, Jenkins to handle parallel testing(no clue how that works), Maven to redeploy to QA on success, or Cucumber will notify through JIRA if testing fails.</p>

<p>There's just too many bits and pieces to make this work and none of the information on the web is precise enough for me to determine which route I should take!</p>

<p>Please share your wisdom!</p>

<p>Thank you so much in advance!</p>
",https://stackoverflow.com/questions/45151608/c-net-bamboo-and-regression-integration-testing-architecture-w-selenium,"['c#', 'selenium', 'cucumber', 'nunit', 'bamboo']",710,TRUE,0,1
Spring Boot ConfigurationProperties fail to initialize for integration testing,"<p>Using gradle (3.4.1) with an integrationTest configuration, the tests using the ConfigurationProperties of Spring Boot (1.5.1.RELEASE) is failing to initialize even though the application initializes correctly (./gradlew bootRun).  The class annotated with ConfigurationProperties is similar to the following</p>

<pre><code>@Component
@ConfigurationProperties(prefix = ""foo"")
@Validated
public class AppConfiguration {
    @NonNull
    private URL serviceUrl;
    ...
</code></pre>

<p>The configuration file does have getters and setters.  The error that is generated is similar to the following</p>

<pre><code>java.lang.IllegalStateException: Failed to load ApplicationContext
....
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AppConfiguration': Could not bind properties to AppConfiguration
....
Caused by: org.springframework.validation.BindException: org.springframework.boot.bind.RelaxedDataBinder$RelaxedBeanPropertyBindingResult
Field error in object 'foo' on field 'serviceUrl': rejected value [null]; codes ...
</code></pre>

<p>The configuration class of the integration test is annotated as follows</p>

<pre><code>@Configuration
@ComponentScan(...)
@EnableConfigurationProperties
@EnableIntegration
public static class ContextConfiguration {}
</code></pre>
",https://stackoverflow.com/questions/42937411/spring-boot-configurationproperties-fail-to-initialize-for-integration-testing,"['gradle', 'spring-boot']",1707,TRUE,0,1
AspNetCore.TestHost - headers middleware raising exceptions under parallel integration testing,"<p>First I create an out-of-the-box template ASP.NET Core MVC web application in Visual Studio.</p>

<p>I then add this Middleware:</p>

<pre><code>public async Task Invoke(HttpContext context)
{
    context.Response.OnStarting(state =&gt;
    {
        var resp = ((HttpContext)state).Response;
        resp.Headers.Add(""MyHeader"", ""header"");
        return Task.CompletedTask;
    }, context);

    await _next.Invoke(context );
}
</code></pre>

<p>This runs fine in a browser, and the header is seen as expected in every page response. Great.</p>

<p>Now I create a test project, add nuget packages 'Microsoft.AspNetCore.TestHost', 'xunit', 'xunit.runners', and put in a test:</p>

<pre><code>    [Fact]
    public void TestHomePageParallel()
    {
        using (var server = CreateServer())
        {
            Parallel.For((long) 0, 10, index =&gt;
            {
                Get(server, ""/"");
            });
        }
    }


    private TestServer CreateServer()
    {
        Environment.SetEnvironmentVariable(""ASPNETCORE_ENVIRONMENT"", ""Development"");
        var directory = Directory.GetCurrentDirectory();
        var setDir = Path.GetFullPath(
            Path.Combine(directory, @""..\..\..\..\..\WebApplication4"")
        );

        var builder = new WebHostBuilder()
            .UseContentRoot(setDir)
            .UseStartup&lt;Startup&gt;();

        return new TestServer(builder);
    }


    public void Get(TestServer server, string url)
    {
        using (var client = server.CreateClient())
        {
            client.BaseAddress = new Uri(""http://localhost:5000"");
            var req = new HttpRequestMessage();
            req.Method = HttpMethod.Get;
            req.RequestUri = new Uri(url, UriKind.Relative);
            var resp = client.SendAsync(req).Result;
            resp.Dispose();
        }
    }
</code></pre>

<p>This will throw Exceptions from the Resp.Headers.Add() code in the Middleware:</p>

<pre><code>One or more errors occurred.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
etc.
</code></pre>

<p>So... Why does this happen?</p>

<p>Note that if you change the test loop to a non-parallel loop, there are no exceptions.</p>

<p>Also note that if you change the middleware code so that the Response.OnStarting() is <em>after</em> the _next.Invoke() call the problem disappears i.e. no exceptions are logged. But every example I have seen of middleware code adding headers does <em>not</em> do it this way around, and I think that it is probably unsafe and/or too late to add the callback this way:</p>

<pre><code>    public async Task Invoke(HttpContext context)
    {    
        await _next.Invoke(context );

        context.Response.OnStarting(state =&gt;
        {
            var resp = ((HttpContext)state).Response;
            resp.Headers.Add(""MyHeader"", ""header"");
            return Task.CompletedTask;
        }, context);
    }
</code></pre>

<p>If you have VS2015 and .net core tools installed, you can download the solution yourself and try it here: <a href=""https://dl.dropboxusercontent.com/u/57858722/HeadersNoWorky.zip"" rel=""nofollow noreferrer"">https://dl.dropboxusercontent.com/u/57858722/HeadersNoWorky.zip</a></p>

<pre><code>Full stack trace:

Test Name:  Test.Integration.TestHomePageParallel
Test FullName:  Test.Integration.TestHomePageParallel
Test Source:    C:\HeadersNoWorky\Test\Test.cs : line 33
Test Outcome:   Failed
Test Duration:  0:00:04.226

Result StackTrace:  
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Parallel.ForWorker64[TLocal](Int64 fromInclusive, Int64 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
   at System.Threading.Tasks.Parallel.For(Int64 fromInclusive, Int64 toExclusive, Action`1 body)
   at Test.Integration.TestHomePageParallel() in C:\HeadersNoWorky\Test\Test.cs:line 36
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Test.Integration.Get(TestServer server, String url) in C:\HeadersNoWorky\Test\Test.cs:line 68
   at Test.Integration.&lt;&gt;c__DisplayClass1_0.&lt;TestHomePageParallel&gt;b__0(Int64 index) in C:\HeadersNoWorky\Test\Test.cs:line 38
   at System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClass18_0`1.&lt;ForWorker64&gt;b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.&lt;&gt;c__DisplayClass176_0.&lt;ExecuteSelfReplicating&gt;b__0(Object )
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Http.HeaderDictionary.Add(String key, StringValues value)
   at WebApplication4.MiddlewareHeader.&lt;&gt;c.&lt;Invoke&gt;b__2_0(Object state) in C:\HeadersNoWorky\WebApplication4\MiddlewareHeader.cs:line 20
   at Microsoft.AspNetCore.TestHost.ResponseFeature.&lt;&gt;c__DisplayClass23_0.&lt;OnStarting&gt;b__0()
   at Microsoft.AspNetCore.TestHost.ResponseFeature.FireOnSendingHeaders()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.GenerateResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.ReturnResponseMessage()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.CompleteResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;&gt;c__DisplayClass3_0.&lt;&lt;SendAsync&gt;b__0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;SendAsync&gt;d__3.MoveNext()
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Test.Integration.Get(TestServer server, String url) in C:\HeadersNoWorky\Test\Test.cs:line 68
   at Test.Integration.&lt;&gt;c__DisplayClass1_0.&lt;TestHomePageParallel&gt;b__0(Int64 index) in C:\HeadersNoWorky\Test\Test.cs:line 38
   at System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClass18_0`1.&lt;ForWorker64&gt;b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.&lt;&gt;c__DisplayClass176_0.&lt;ExecuteSelfReplicating&gt;b__0(Object )
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Http.HeaderDictionary.Add(String key, StringValues value)
   at WebApplication4.MiddlewareHeader.&lt;&gt;c.&lt;Invoke&gt;b__2_0(Object state) in C:\HeadersNoWorky\WebApplication4\MiddlewareHeader.cs:line 20
   at Microsoft.AspNetCore.TestHost.ResponseFeature.&lt;&gt;c__DisplayClass23_0.&lt;OnStarting&gt;b__0()
   at Microsoft.AspNetCore.TestHost.ResponseFeature.FireOnSendingHeaders()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.GenerateResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.ReturnResponseMessage()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.CompleteResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;&gt;c__DisplayClass3_0.&lt;&lt;SendAsync&gt;b__0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;SendAsync&gt;d__3.MoveNext()
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Test.Integration.Get(TestServer server, String url) in C:\HeadersNoWorky\Test\Test.cs:line 68
   at Test.Integration.&lt;&gt;c__DisplayClass1_0.&lt;TestHomePageParallel&gt;b__0(Int64 index) in C:\HeadersNoWorky\Test\Test.cs:line 38
   at System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClass18_0`1.&lt;ForWorker64&gt;b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.&lt;&gt;c__DisplayClass176_0.&lt;ExecuteSelfReplicating&gt;b__0(Object )
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Http.HeaderDictionary.Add(String key, StringValues value)
   at WebApplication4.MiddlewareHeader.&lt;&gt;c.&lt;Invoke&gt;b__2_0(Object state) in C:\HeadersNoWorky\WebApplication4\MiddlewareHeader.cs:line 20
   at Microsoft.AspNetCore.TestHost.ResponseFeature.&lt;&gt;c__DisplayClass23_0.&lt;OnStarting&gt;b__0()
   at Microsoft.AspNetCore.TestHost.ResponseFeature.FireOnSendingHeaders()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.GenerateResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.ReturnResponseMessage()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.CompleteResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;&gt;c__DisplayClass3_0.&lt;&lt;SendAsync&gt;b__0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;SendAsync&gt;d__3.MoveNext()
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Test.Integration.Get(TestServer server, String url) in C:\HeadersNoWorky\Test\Test.cs:line 68
   at Test.Integration.&lt;&gt;c__DisplayClass1_0.&lt;TestHomePageParallel&gt;b__0(Int64 index) in C:\HeadersNoWorky\Test\Test.cs:line 38
   at System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClass18_0`1.&lt;ForWorker64&gt;b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.&lt;&gt;c__DisplayClass176_0.&lt;ExecuteSelfReplicating&gt;b__0(Object )
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Http.HeaderDictionary.Add(String key, StringValues value)
   at WebApplication4.MiddlewareHeader.&lt;&gt;c.&lt;Invoke&gt;b__2_0(Object state) in C:\HeadersNoWorky\WebApplication4\MiddlewareHeader.cs:line 20
   at Microsoft.AspNetCore.TestHost.ResponseFeature.&lt;&gt;c__DisplayClass23_0.&lt;OnStarting&gt;b__0()
   at Microsoft.AspNetCore.TestHost.ResponseFeature.FireOnSendingHeaders()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.GenerateResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.ReturnResponseMessage()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.CompleteResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;&gt;c__DisplayClass3_0.&lt;&lt;SendAsync&gt;b__0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;SendAsync&gt;d__3.MoveNext()
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Test.Integration.Get(TestServer server, String url) in C:\HeadersNoWorky\Test\Test.cs:line 68
   at Test.Integration.&lt;&gt;c__DisplayClass1_0.&lt;TestHomePageParallel&gt;b__0(Int64 index) in C:\HeadersNoWorky\Test\Test.cs:line 38
   at System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClass18_0`1.&lt;ForWorker64&gt;b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.&lt;&gt;c__DisplayClass176_0.&lt;ExecuteSelfReplicating&gt;b__0(Object )
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Http.HeaderDictionary.Add(String key, StringValues value)
   at WebApplication4.MiddlewareHeader.&lt;&gt;c.&lt;Invoke&gt;b__2_0(Object state) in C:\HeadersNoWorky\WebApplication4\MiddlewareHeader.cs:line 20
   at Microsoft.AspNetCore.TestHost.ResponseFeature.&lt;&gt;c__DisplayClass23_0.&lt;OnStarting&gt;b__0()
   at Microsoft.AspNetCore.TestHost.ResponseFeature.FireOnSendingHeaders()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.GenerateResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.ReturnResponseMessage()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.CompleteResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;&gt;c__DisplayClass3_0.&lt;&lt;SendAsync&gt;b__0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;SendAsync&gt;d__3.MoveNext()
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Test.Integration.Get(TestServer server, String url) in C:\HeadersNoWorky\Test\Test.cs:line 68
   at Test.Integration.&lt;&gt;c__DisplayClass1_0.&lt;TestHomePageParallel&gt;b__0(Int64 index) in C:\HeadersNoWorky\Test\Test.cs:line 38
   at System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClass18_0`1.&lt;ForWorker64&gt;b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.&lt;&gt;c__DisplayClass176_0.&lt;ExecuteSelfReplicating&gt;b__0(Object )
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Http.HeaderDictionary.Add(String key, StringValues value)
   at WebApplication4.MiddlewareHeader.&lt;&gt;c.&lt;Invoke&gt;b__2_0(Object state) in C:\HeadersNoWorky\WebApplication4\MiddlewareHeader.cs:line 20
   at Microsoft.AspNetCore.TestHost.ResponseFeature.&lt;&gt;c__DisplayClass23_0.&lt;OnStarting&gt;b__0()
   at Microsoft.AspNetCore.TestHost.ResponseFeature.FireOnSendingHeaders()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.GenerateResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.ReturnResponseMessage()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.CompleteResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;&gt;c__DisplayClass3_0.&lt;&lt;SendAsync&gt;b__0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;SendAsync&gt;d__3.MoveNext()
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Test.Integration.Get(TestServer server, String url) in C:\HeadersNoWorky\Test\Test.cs:line 68
   at Test.Integration.&lt;&gt;c__DisplayClass1_0.&lt;TestHomePageParallel&gt;b__0(Int64 index) in C:\HeadersNoWorky\Test\Test.cs:line 38
   at System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClass18_0`1.&lt;ForWorker64&gt;b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.&lt;&gt;c__DisplayClass176_0.&lt;ExecuteSelfReplicating&gt;b__0(Object )
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Http.HeaderDictionary.Add(String key, StringValues value)
   at WebApplication4.MiddlewareHeader.&lt;&gt;c.&lt;Invoke&gt;b__2_0(Object state) in C:\HeadersNoWorky\WebApplication4\MiddlewareHeader.cs:line 20
   at Microsoft.AspNetCore.TestHost.ResponseFeature.&lt;&gt;c__DisplayClass23_0.&lt;OnStarting&gt;b__0()
   at Microsoft.AspNetCore.TestHost.ResponseFeature.FireOnSendingHeaders()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.GenerateResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.ReturnResponseMessage()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.CompleteResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;&gt;c__DisplayClass3_0.&lt;&lt;SendAsync&gt;b__0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;SendAsync&gt;d__3.MoveNext()
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Test.Integration.Get(TestServer server, String url) in C:\HeadersNoWorky\Test\Test.cs:line 68
   at Test.Integration.&lt;&gt;c__DisplayClass1_0.&lt;TestHomePageParallel&gt;b__0(Int64 index) in C:\HeadersNoWorky\Test\Test.cs:line 38
   at System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClass18_0`1.&lt;ForWorker64&gt;b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.&lt;&gt;c__DisplayClass176_0.&lt;ExecuteSelfReplicating&gt;b__0(Object )
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Http.HeaderDictionary.Add(String key, StringValues value)
   at WebApplication4.MiddlewareHeader.&lt;&gt;c.&lt;Invoke&gt;b__2_0(Object state) in C:\HeadersNoWorky\WebApplication4\MiddlewareHeader.cs:line 20
   at Microsoft.AspNetCore.TestHost.ResponseFeature.&lt;&gt;c__DisplayClass23_0.&lt;OnStarting&gt;b__0()
   at Microsoft.AspNetCore.TestHost.ResponseFeature.FireOnSendingHeaders()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.GenerateResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.ReturnResponseMessage()
   at Microsoft.AspNetCore.TestHost.ClientHandler.RequestState.CompleteResponse()
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;&gt;c__DisplayClass3_0.&lt;&lt;SendAsync&gt;b__0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.TestHost.ClientHandler.&lt;SendAsync&gt;d__3.MoveNext()
Result Message: 
One or more errors occurred.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
An item with the same key has already been added.
One or more errors occurred.
An item with the same key has already been added.
</code></pre>

<p><strong>UPDATE:</strong>
After adding some debug, I can see that Response.OnStarting() is being called more than once for the same request, so it is trying to update the response headers twice for a single request, causing the exception. Unfortunately, I can't see why Response.OnStarting() would be called twice.</p>
",https://stackoverflow.com/questions/42890322/aspnetcore-testhost-headers-middleware-raising-exceptions-under-parallel-integ,"['asp.net', 'unit-testing', 'asp.net-core', 'asp.net-core-mvc', 'asp.net-core-middleware']",1022,TRUE,0,1
Integration testing strategy for Web API actions with attributes,"<p>I am working on ASP.NET Core WebApi.  We have action methods decorated with custom attributes.  eg </p>

<pre><code>[CheckPermission(Permissions.View)]
public IHttpActionResult Get()
{
}
</code></pre>

<p>CheckPermission attribute lives in shared library and will be used by other Api's too.</p>

<p>CheckPermisision attribute internally makes httpclient call to api to get boolean true or false and returns appropriate status code if unauthorized.</p>

<p>How should i approach for integration testing above action method. Am using inmemory test server to host my api in memory and then i use xunit to run test on it.  I am worried that if i do setup of data for permissions too then unit test code will be come very messy.</p>
",https://stackoverflow.com/questions/43458749/integration-testing-strategy-for-web-api-actions-with-attributes,"['c#', 'asp.net-core', 'integration-testing', 'asp.net-core-webapi']",473,TRUE,0,1
Integration testing of React front end with Django REST backend,"<p>Does anybody know how to do <strong>integration testing</strong> of a (React) frontend with Django REST backend. I was able to write functional tests for the frontend with Nightwatch.js and with a fake server API. I am also able to separately test Django REST API - Django offers a LiveServerTestCase that can start a test server for you with a test database and destroy it at the end. I'm wondering if it's possible to somehow use/setup Django's test server that can be called by the front end (i.e. Nightwatch tests).
I'm open to other ideas on how I can approach this problem. </p>
",https://stackoverflow.com/questions/43637221/integration-testing-of-react-front-end-with-django-rest-backend,"['django', 'reactjs', 'testing', 'django-rest-framework', 'integration-testing']",1791,TRUE,5,1
Typescript / Node.js - How to mock transitive dependencies for integration testing?,"<p>Let say I have an Express route which is handled by a controller. The controller uses a service and the service uses a repository to talk to a data source.</p>

<p>I want to create an integration test using <a href=""https://github.com/visionmedia/supertest"" rel=""noreferrer"">Supertest</a> to test that route :  </p>

<pre><code>test -&gt; my Express app -&gt; controller -&gt; service -&gt; repository -&gt; data source
</code></pre>

<p>My problem is that I need to <em>mock</em> the repository/data source, to run the test! I want to hardcode some values as if they were coming from the real data source. What are my options?</p>

<p>In a Java world, I would be using dependency injection with Spring or Guice and I would replace the repository with a mock version that way. What are the patterns to achieve such mocking in a Typescript/Node.js world?</p>

<p>I guess using plain Javascript I could use <code>Proxyquire</code> and its <a href=""https://github.com/thlorenz/proxyquire#globally-override-require"" rel=""noreferrer"">Globally override require</a> feature, to mock the repository from the test itself. But I'm not sure this works well with Typescript.</p>

<p>So what are the recommended ways of mocking a ""deep"" component (a transitive dependency) from within a test file, using Typescript and Node.js?</p>
",https://stackoverflow.com/questions/42497368/typescript-node-js-how-to-mock-transitive-dependencies-for-integration-testi,"['node.js', 'typescript', 'supertest', 'proxyquire']",2893,TRUE,5,1
How to integration testing of internal POST requests using Django?,"<p>I have a Django project using Django Rest Framework with two apps (<code>events</code> and <code>logs</code>) and associated endpoints <code>/events</code> and <code>/logs</code></p>

<p>Clients can POST to <code>/events</code> some information about an event, the processing of this will record a log in the <code>logs</code> app model. The logs can then be retrieved using GET on <code>/logs</code>.</p>

<p>Whilst the events view can update through the logs view directly, I wanted to implement this through a POST call to <code>/logs</code> call to keep the interfaces more well defined and easier to split out into a completely separate service if required. The POST call is handled using <code>requests</code> package as follows:</p>

<pre><code>from rest_framework.views import APIView
import requests

class Events(APIView):

    def post(self, request):

        # Some event handling code...

        # Record log
        log_url = request.build_absolute_uri(reverse('logs'))
        requests.post(log_url, data=event)
</code></pre>

<p>To test this works I boot up the server and do:</p>

<ul>
<li>POST /events/ (post some JSON data)</li>
<li>GET /logs/</li>
</ul>

<p>In this case I see some log data returned from the GET request, so I know that e2e the implementation works. However, when I try to automate this using <code>django.test.LiveServerTestCase</code> the response is always empty.</p>

<pre><code>from django.test import LiveServerTestCase
from rest_framework.test import RequestsClient

class AppsEndpointTest(LiveServerTestCase):

    def test_post_event_retrieve_logs(self):

        events_endpoint = self.live_server_url + '/events/'
        logs_endpoint = self.live_server_url + '/logs/'
        client = RequestsClient()

        # POST an application which we know will trigger an event
        client.post(events_endpoint, { 'event_code' : 'TEST_EVENT' })

        # Check the event is returned
        response = client.get(logs_endpoint)

        self.assertEqual(response.status_code, 200)
        self.assertIn('TEST_EVENT', [log['event_code'] for logs in response.json()])
        # Assertion fails, response is empty
</code></pre>

<p>I am assuming the call to <code>request.build_absolute_uri()</code> is part of the problem and that the request that comes in doesn't have a proper hostname to build the URL from. I can't see any of the server logging when the test case is run, which has led me to this blocking point.</p>

<p>Why doesn't this work when using <code>LiveServerTestCase</code>?</p>
",https://stackoverflow.com/questions/41650962/how-to-integration-testing-of-internal-post-requests-using-django,"['python', 'django', 'django-rest-framework']",1016,FALSE,2,0
Integration Testing and Load Testing : using the same scenarii (JVM),"<p>At the moment, I'm using two different frameworks for REST APIs integration testing, and load/stress testing. Respectively : <a href=""http://gebish.org"" rel=""nofollow noreferrer"">geb</a> (or cucumber) and <a href=""http://gatling.io"" rel=""nofollow noreferrer"">gatling</a>. But most of the time, I'm re-writing some  pieces of code in load / performance scenarii that I've been writing for integration testing.</p>

<p>So the question is : is there a framework (running on the JVM) or simply a way, to write integration tests (for a strict REST API use case), preferably programmatically, then assemble load testing scenarios using these integration tests.</p>

<p>I've read <a href=""http://blog.mattwynne.net/2012/03/13/using-cucumber-for-load-testing/"" rel=""nofollow noreferrer"">cucumber</a> maybe could do that, but I'm lacking a proper example.</p>

<p>The requirements : </p>

<ul>
<li><p>write integration tests programmatically</p></li>
<li><p>for any integration test, have the ability to ""extract"" values (the same way gatling can extract json paths for instance)</p></li>
<li><p>assemble the integration tests in a load test scenario</p></li>
</ul>

<p>If anyone has some experience to share, I'd be happy to read any blog article, GitHub repository, or whatever source dealing with such an approach.</p>

<p>Thanks in advance for your help.</p>
",https://stackoverflow.com/questions/44434546/integration-testing-and-load-testing-using-the-same-scenarii-jvm,"['cucumber', 'integration-testing', 'load-testing', 'geb', 'gatling']",476,TRUE,1,1
Automapper fails to initialize in asp.net core Integration Testing project,"<p>I am getting null reference exception while doing integration testing in aspnetcore project. The project is aspnetcore webapi project that uses full .net framework. The automapper initialization works for the actual webapi project but it fails for integration testing class library project during the dependency injection process. </p>

<p><strong>Exception:</strong></p>

<p><a href=""https://i.stack.imgur.com/Qs9lF.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Qs9lF.png"" alt=""services.AddAutoMapper()""></a></p>

<p><strong>Exception Stacktrace:</strong></p>

<pre><code>System.ArgumentNullException occurred
  HResult=0x80004003
  Message=Value cannot be null.
  Source=Microsoft.Extensions.DependencyModel
  StackTrace:
   at Microsoft.Extensions.DependencyModel.DependencyContextLoader.Load(Assembly assembly)
   at Microsoft.Extensions.DependencyModel.DependencyContext.LoadDefault()
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at System.Lazy`1.get_Value()
   at AutoMapper.ServiceCollectionExtensions.AddAutoMapper(IServiceCollection services)
   at EI.CatalogBuilder.WebService.Startup.ConfigureServices(IServiceCollection services) in F:\ei_cube_customization\EI.CatalogBuilder\EI.CatalogBuilder.WebService\Startup.cs:line 154
</code></pre>

<p><strong>Integration Test Project (packages.config):</strong></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;packages&gt;
  &lt;package id=""AutoMapper"" version=""6.1.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""AutoMapper.Extensions.Microsoft.DependencyInjection"" version=""2.0.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""EntityFramework"" version=""6.1.3"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Antiforgery"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Authorization"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Cryptography.Internal"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.DataProtection"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.DataProtection.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Diagnostics.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Hosting"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Hosting.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Hosting.Server.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Html.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Http"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Http.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Http.Extensions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Http.Features"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.JsonPatch"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Mvc.Abstractions"" version=""1.1.3"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Mvc.Core"" version=""1.1.3"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Mvc.DataAnnotations"" version=""1.1.3"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Mvc.Formatters.Json"" version=""1.1.3"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Mvc.ViewFeatures"" version=""1.1.3"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.ResponseCaching.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Routing"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.Routing.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.TestHost"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.AspNetCore.WebUtilities"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.CSharp"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.DotNet.PlatformAbstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.Configuration"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.Configuration.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.Configuration.EnvironmentVariables"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.DependencyInjection"" version=""1.1.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.DependencyInjection.Abstractions"" version=""1.1.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.DependencyModel"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.FileProviders.Abstractions"" version=""1.1.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.FileProviders.Physical"" version=""1.1.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.FileSystemGlobbing"" version=""1.1.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.Localization"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.Localization.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.Logging"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.Logging.Abstractions"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.ObjectPool"" version=""1.1.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.Options"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.PlatformAbstractions"" version=""1.1.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.Primitives"" version=""1.1.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Extensions.WebEncoders"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Net.Http.Headers"" version=""1.1.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.NETCore.Platforms"" version=""1.1.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""Microsoft.Win32.Primitives"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""NETStandard.Library"" version=""1.6.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""Newtonsoft.Json"" version=""10.0.3"" targetFramework=""net46"" /&gt;
  &lt;package id=""NSubstitute"" version=""2.0.3"" targetFramework=""net46"" /&gt;
  &lt;package id=""NUnit"" version=""3.7.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""NUnit3TestAdapter"" version=""3.8.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.AppContext"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Buffers"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Collections"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Collections.Concurrent"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Collections.Immutable"" version=""1.3.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.ComponentModel"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Console"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Diagnostics.Contracts"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Diagnostics.Debug"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Diagnostics.DiagnosticSource"" version=""4.4.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Diagnostics.Tools"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Diagnostics.Tracing"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Globalization"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Globalization.Calendars"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.IO"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.IO.Compression"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.IO.Compression.ZipFile"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.IO.FileSystem"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.IO.FileSystem.Primitives"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Linq"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Linq.Expressions"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Net.Http"" version=""4.3.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Net.Primitives"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Net.Sockets"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.ObjectModel"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Reflection"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Reflection.Extensions"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Reflection.Metadata"" version=""1.4.2"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Reflection.Primitives"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Resources.ResourceManager"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Runtime"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Runtime.CompilerServices.Unsafe"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Runtime.Extensions"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Runtime.Handles"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Runtime.InteropServices"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Runtime.InteropServices.RuntimeInformation"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Runtime.Numerics"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Security.Cryptography.Algorithms"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Security.Cryptography.Encoding"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Security.Cryptography.Primitives"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Security.Cryptography.X509Certificates"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Text.Encoding"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Text.Encoding.Extensions"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Text.Encodings.Web"" version=""4.3.1"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Text.RegularExpressions"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Threading"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Threading.Tasks"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Threading.Timer"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Xml.ReaderWriter"" version=""4.3.0"" targetFramework=""net46"" /&gt;
  &lt;package id=""System.Xml.XDocument"" version=""4.3.0"" targetFramework=""net46"" /&gt;
&lt;/packages&gt;</code></pre>
</div>
</div>
</p>

<p><strong>Web API Project (packages):</strong></p>

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

<p><strong>Startup.cs:</strong></p>

<pre><code>using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Mvc.Versioning;
using EI.CatalogBuilder.ActiveDirectory.Identity.Models;
using Microsoft.AspNetCore.Identity;
using EI.CatalogBuilder.ActiveDirectory.Identity.Stores;
using EI.CatalogBuilder.ActiveDirectory.Identity.DataAccess;
using EI.CatalogBuilder.WebService.Utils.SecurityPolicies;
using Microsoft.AspNetCore.Authorization;
using EI.CatalogBuilder.WebService.Utils.SecurityPolicies.Handlers;
using EI.CatalogBuilder.WebService.Utils;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using NLog.Extensions.Logging;
using NLog.Web;
using Microsoft.AspNetCore.Http;
using EI.CatalogBuilder.WebService.Repositories;
using EI.CatalogBuilder.Infrastructure.Data;
using AutoMapper;

namespace EI.CatalogBuilder.WebService
{
    public class Startup
    {
        private readonly IHostingEnvironment _env;
        private readonly ConfigReader _configReader;

        private IConfigurationRoot _config { get; }


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

            _configReader = new ConfigReader(_config);
            _env = env;

            _env.ConfigureNLog(""nlog.config"");
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_config);
            services.AddSingleton(_configReader);

            services.AddTransient&lt;ModuleRepository, ModuleRepository&gt;();
            services.AddTransient&lt;ClientRepository, ClientRepository&gt;();
            services.AddTransient&lt;CatalogBuilderUnitOfWork, CatalogBuilderUnitOfWork&gt;();

            services.AddSingleton&lt;IAuthorizationHandler, DevelopersRequirementHandler&gt;();
            services.AddSingleton&lt;IAuthorizationHandler, PublishersRequirementHandler&gt;();
            services.AddSingleton&lt;IAuthorizationHandler, ViewersRequirementHandler&gt;();

            services.AddTransient&lt;IUserContext&lt;User&gt;, ActiveDirectoryUserContext&gt;();
            services.AddTransient&lt;IRoleContext&lt;Role&gt;, ActiveDirectoryRoleContext&gt;();

            // Add framework services.

            // Add identity types
            services.AddIdentity&lt;User, Role&gt;()
                .AddDefaultTokenProviders();

            // Identity Services
            services.AddTransient&lt;IUserStore&lt;User&gt;, UserStore&lt;User&gt;&gt;();
            services.AddTransient&lt;IRoleStore&lt;Role&gt;, RoleStore&lt;Role&gt;&gt;();

            services.Configure&lt;IdentityOptions&gt;(options =&gt;
            {
                options.Cookies.ApplicationCookie.Events =
                    new CookieAuthenticationEvents
                    {
                        OnRedirectToLogin = (ctx) =&gt;
                        {
                            if (ctx.Response.StatusCode == 200)
                            {
                                ctx.Response.StatusCode = 401;
                            }

                            return Task.CompletedTask;
                        },

                        OnRedirectToAccessDenied = (ctx) =&gt;
                        {
                            if (ctx.Response.StatusCode == 200)
                            {
                                ctx.Response.StatusCode = 403;
                            }

                            return Task.CompletedTask;
                        }
                    };
            });

            services.AddApiVersioning(configuration =&gt; {
                var majorVersion = _configReader.GetApiMajorVersion();
                var minorVersion = _configReader.GetApiMinorVersion();

                configuration.DefaultApiVersion = new ApiVersion(majorVersion, minorVersion);
                configuration.AssumeDefaultVersionWhenUnspecified = true;
                configuration.ReportApiVersions = true;

                configuration.ApiVersionReader = new HeaderApiVersionReader(""ver"");
            });

            services.AddCors(configuration =&gt;
            {
                configuration.AddPolicy(""Default"", builder =&gt;
                {
                    builder.AllowAnyHeader()
                        .AllowAnyMethod()
                        .WithOrigins(_configReader.GetCorsDefaultOrigin());
                });
            });

            services.AddAuthorization(configuration =&gt;
            {
                configuration.AddPolicy(""Developers"", policy =&gt; policy.Requirements.Add(new DevelopersRequirement()));
                configuration.AddPolicy(""Publishers"", policy =&gt; policy.Requirements.Add(new PublishersRequirement()));
                configuration.AddPolicy(""Viewers"", policy =&gt; policy.Requirements.Add(new ViewersRequirement()));
            });

            services.AddMvc(options =&gt;
            {
                // We are supporting SSL for all environments but the development environment
                if (!_env.IsDevelopment())
                {
                    options.Filters.Add(new RequireHttpsAttribute());
                }
            })
            .AddJsonOptions(options =&gt;
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

            services.Configure&lt;MvcOptions&gt;(options =&gt;
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory(""Default""));
            });

            services.AddAutoMapper();

            services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();
            app.AddNLogWeb();

            app.UseIdentity();

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer = _configReader.GetJwtTokenIssuer(),
                    ValidAudience = _configReader.GetJwtTokenAudience(),
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configReader.GetJwtTokenKey())),
                    ValidateLifetime = true
                }
            });

            app.UseMvc();
        }
    }
}
</code></pre>

<p><strong>Integration Test Class:</strong></p>

<pre><code>using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using NUnit.Framework;
using System.Net.Http;
using System.Threading.Tasks;

namespace EI.CatalogBuilder.WebService.Tests.IntegrationTests
{
    public class EntityControllerTests
    {
        private readonly TestServer _server;
        private readonly HttpClient _client;

        public EntityControllerTests()
        {
            _server = new TestServer(new WebHostBuilder()

                .UseStartup&lt;Startup&gt;());
            _client = _server.CreateClient();
        }

        [Test]
        public async Task GetRetunsEmptyListInitially()
        {
            var request = ""/api/Modules"";

            var response = await _client.GetAsync(request);
            response.EnsureSuccessStatusCode();

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

            // Assert
            Assert.AreEqual(""[]"", responseString);
        }

    }
}
</code></pre>
",https://stackoverflow.com/questions/45398125/automapper-fails-to-initialize-in-asp-net-core-integration-testing-project,"['c#', 'asp.net-core', 'asp.net-core-mvc', 'automapper', 'asp.net-core-webapi']",957,TRUE,0,1
Test Cases for Integration Testing for Instant Messaging Chat App,"<p>I have created a Instant Messaging Chat App using Telegram Open Source Code for my College Project. Most of the functionality are similar to WhatsApp. I have created Test Cases for Unit Testing. But stuck in writing test cases for Integration Testing because exactly I don't know what to write in test case for integration testing.
Here I have attached test cases Format/Template for Unit testing. </p>

<p><a href=""https://i.stack.imgur.com/aJNKw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/aJNKw.png"" alt=""Test Cases for Unit Testing""></a></p>

<p>Please suggest test cases with Expected Input and Expected result for Integration testing-</p>
",https://stackoverflow.com/questions/44033914/test-cases-for-integration-testing-for-instant-messaging-chat-app,"['android', 'unit-testing', 'testing', 'integration-testing']",3499,FALSE,0,1
How to get relative path in Integration Testing in c#,"<h2>Problem</h2>
<p>I am trying to test my importing service in which I have to provide file which is save in the same solution but different folder and also there are bunch of project in it too and this folder is out of the projects. I want this path to be absolute path how can I do this?</p>
<p>I am doing in this way</p>
<pre><code>string filePath = Path.GetFullPath(@&quot;E:\Development\Project\Misc Artifacts\ImportFileSamples\city.txt&quot;);
</code></pre>
",https://stackoverflow.com/questions/42048830/how-to-get-relative-path-in-integration-testing-in-c,['c#'],195,FALSE,-1,2
Rails Integration Testing: Is Capybara necessary for interacting with Javascript?,"<p>I'm new to testing in Rails and I'm trying to get into integration testing. I'm working with a Rails 4.2 project and I've written some simple tests in the default Minitest framework. I've quickly got to the point where I need to interact with javascript in the html by clicking a button and verifying that a modal appears.</p>

<p>From the research that I've done, it doesn't seem to be possible to to do anything like this with the syntax and driver that comes with Minitest. In order to do this I need to use Caypbara or something equivalent.</p>

<p>Firstly - Is that really the case? is there really no way to test Javascript with the default setup in Rails?</p>

<p>Assuming that is the case, I've pulled in Capybara to my project to utilize it's DSL and drivers for testing Javascript, but in doing so, it has rendered my initial tests useless. They no longer work as the Capybara DSL overwrites the <code>assert_select</code> method, forcing me to use Capybara syntax for writing tests - not something that I'm against, I'm just figuring this out.  </p>

<p>So it seems like that if I ever want to test Javascript, then I need to use Capybara? and if I pull in Capybara then all my tests need to use Capybara syntax? If this is true, then it seems like I should just use Capybara from the get-go on all projects.</p>
",https://stackoverflow.com/questions/43693667/rails-integration-testing-is-capybara-necessary-for-interacting-with-javascript,"['ruby-on-rails', 'ruby', 'ruby-on-rails-4', 'testing']",556,TRUE,0,1
Integration testing using @SpringApplicationConfiguration with mocks not working in Jenkins,"<p>There is something weird going on with my integration test when it runs in Jenkins, it fails to wire primary beans which are mocks. </p>

<p>However, when run locally using Maven install, it works flawlessly. This is my integration test:</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {App.class, SampleIT.class})
@WebIntegrationTest({""server.port:0""})
public class SampleIT {

    @Primary
    @Bean    
    public SampleRepository sampleRepository() { //this is wired fine in my local Maven, but not in Jenkins...
        return Mockito.mock(Sample.class);
    }

    @Test
    public void testSomething {
        //when this is executed, the mock has been wired at this point in my local Maven
        //however in Jenkins, it still uses the real SampleRepositoryImpl, not the mock
    }
}
</code></pre>

<p>This the App.class, which is a Spring Boot app:</p>

<pre><code>@SpringBootApplication
@EnableAspectJAutoProxy
@EnableDiscoveryClient
@ComponentScan(""com.sample"")
@EnableJpaRepositories(""com.sample"")
@EntityScan(""com.sample"")
@DependsOn(""OAuth2Config"")
public class App extends SpringBootServletInitializer {
    public static void main(final String[] args) {
        SpringApplication.run(App.class, args);
    }
}
</code></pre>

<p>I can certainly see that Jenkins is using the real SampleRepositoryImpl instead of the mock, because of the generated sql statements in the Jenkins console. Unlike in my local Maven, there are no generate sqls since it is using the mock. </p>

<p>Has anyone else experience this? </p>

<p>How to solve this issue, so that running in Jenkins will also use the mock, which is marked as primary bean?</p>

<p><strong>--------- UPDATE ---------</strong></p>

<p>If I:</p>

<ol>
<li>remove SampleIT.class from @SpringApplicationConfiguration </li>
<li>and add @Configuration to the SampleIT</li>
</ol>

<p>it works, mocks are wired. HOWEVER, this becomes a global config and my other integration tests starts picking up the mocks defined in this class. So its not really a solution, any ideas why @SpringApplicationConfiguration  does not seem to work?</p>
",https://stackoverflow.com/questions/43359945/integration-testing-using-springapplicationconfiguration-with-mocks-not-working,"['jenkins', 'spring-boot', 'junit', 'mockito', 'integration-testing']",797,FALSE,0,1
How should I approach integration testing for APIs involving Facebook?,"<p><strong>The scenario</strong></p>

<p>Suppose there is a mobile app connected to a backend API (nodejs, though not that important), and you can ""register with Facebook"". </p>

<p>Registering with Facebook implies a couple of steps: on the mobile part the user authorises FB access, FB provides the app with a token, that token is sent to the server and (let's suppose using a passport-facebook strategy) that token can be sent again to FB along with app credentials so that FB can transform that token into a User object.</p>

<p>Suppose on the backend side you use that User object to create your own App User entry, fetch the profile picture and store it, etc. And by manually testing you can see that the User object has a specific structure: an <code>id</code> field, an <code>emails</code> field (which is an array with a complex structure), etc. You end up writing you registration steps based on that.</p>

<p><strong>The problem</strong></p>

<p>While I know that the FB returned User object looked in a certain way at a certain point in time I cannot be sure it will be the same in the future and I won't get an ""cannot access something of undefined"" error message when they decide to change the structure of that. On the other hand I would really like to have integration tests that include third party integrations, like FB.</p>

<p>I know that you can have (virtual) FB test users and I checked out their documentation for testing, it only shows example of Mobile app testing as far as I know, no backend oriented testing.</p>

<p>I would ideally need to be able to either fetch a (test or not) FB User with which I can test out my registration process or even better a token that can be used in the whole API flow, so that the whole process is covered. Any ideas where I should look or if it is worth investing in this direction?</p>
",https://stackoverflow.com/questions/47432193/how-should-i-approach-integration-testing-for-apis-involving-facebook,"['facebook', 'facebook-graph-api', 'integration-testing', 'passport-facebook']",326,FALSE,0,0
How to trace an Entity Framework Core event for integration testing?,"<p>We need to ensure that EF Core-based code has performed a specific kind of database-level operation under test (for example, <em>any</em> command execution or <em>any</em> transaction commit).  </p>

<p>Let's suppose a real database should be triggered and we can't isolate it by <code>DbContext</code> mocking. How could it look:</p>

<pre><code>[Fact]
public async Task Test()
{
    using (var context = new FooContext())
    {
        //context-related code to produce queries and commands
    }

    Assert.True(/* any context-related transaction has been committed */);
}
</code></pre>

<p>Is it possible?</p>
",https://stackoverflow.com/questions/44094762/how-to-trace-an-entity-framework-core-event-for-integration-testing,"['c#', '.net-core', 'entity-framework-core']",2401,TRUE,4,1
Android automated Integration Testing with Semaphoreci. How to properly set up?,"<p><a href=""https://semaphoreci.com"" rel=""nofollow noreferrer"">https://semaphoreci.com</a></p>

<p>I have an Android project I'm working on I'm trying to set up automated integration testing on every PR against my master branch on GitHub with semaphoreci.</p>

<p>The question I have is, how can I run the gradle tasks if there is no Android SDK? Do I have to push my Android SDK (really don't wanna)? Or can I point to a compiled Android SDK on a server (possibly Google)?</p>

<p>So far I have it set up semaphoreci to run these commands:</p>

<pre><code>gradle wrapper // Fails here
./gradlew clean
./gradlew build
</code></pre>

<p>I get this error</p>

<pre><code>FAILURE: Build failed with an exception.
[0K
* What went wrong:
A problem occurred configuring project ':app'.
&gt; SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.
</code></pre>
",https://stackoverflow.com/questions/46121821/android-automated-integration-testing-with-semaphoreci-how-to-properly-set-up,"['android', 'github', 'gradle', 'continuous-integration', 'semaphore-ci']",262,FALSE,2,1
Should I mix integration testing and rest documentation with Spring Boot?,"<p>Spring Rest Documentation (spring-restdocs) is a very good replacement for Swagger when working with Spring Boot. Is it better to mix integration tests with Rest documentation tests or to create separate Rest documentation tests even if some tests are duplicated?</p>
",https://stackoverflow.com/questions/42089201/should-i-mix-integration-testing-and-rest-documentation-with-spring-boot,"['spring-boot', 'integration-testing', 'spring-restdocs']",135,TRUE,1,1
How to assert csv file content exists in laravel integration testing,"<p>I am doing integration testing for a csv file download. I need to know is there a way to check the file content when running the test case?</p>
",https://stackoverflow.com/questions/44195625/how-to-assert-csv-file-content-exists-in-laravel-integration-testing,"['php', 'laravel', 'csv', 'integration-testing']",993,TRUE,-1,1
Having Non-Test Methods with assertions in xUnit or Integration Testing,"<p>There is a question-discussion <a href=""https://stackoverflow.com/questions/137399/unit-testing-without-assertions"">about having unit tests without assertions.</a> But there is also another question which might need some discussion:</p>

<p>Is it a good practice to have non-test method(s) having assertions in xUnit or Integration test class, which is(are) used in test methods inside the same or other test classes?</p>

<p><strong>EDIT:</strong> How to implement a case, when you have several test cases which are required to run in a specific order and running in that order those multiple test cases construct another test case? Is it good to implement those test cases as non-test methods with assertions and then have one test method which calls all these chained methods in an order?</p>
",https://stackoverflow.com/questions/43663438/having-non-test-methods-with-assertions-in-xunit-or-integration-testing,"['java', 'unit-testing', 'continuous-integration', 'integration-testing']",883,FALSE,0,0
How to get a SAML Response from OKTA for unit/integration testing,"<p>I am working on project where they are authenticating via SAML from OKTA.  I have successfully got the integration working where a SAMLResponse sent (via POST method) to the website.  </p>

<p>In true TDD fashion, I started by writing some unit tests.  My unit tests take in a SAMLResponse (which is Base64 encoded).  All my unit tests work, however, because a SAMLResponse only have a lifetime (expires) of a few minutes, my unit tests break after a few minutes.</p>

<p>So I need to periodically login to OKTA, then using Chrome dev tools capture the traffic being sent to my dev site.  I then copy and paste the SAMLResponse into my unit tests and get back to passing unit tests.  Obviously this is not a desirable situation.  </p>

<p>So my question is how can I login to Okta in an automated fashion (preferably in C#) to get a SAMLResponse?  I assume there is some URL I can POST to with username and password and get back the SAMLReponse.  All my Fiddler attempts at trying to understand the required communicate has left me frustrated.  I am looking for any guidance you might have.  Thanks in advance.</p>
",https://stackoverflow.com/questions/41639609/how-to-get-a-saml-response-from-okta-for-unit-integration-testing,"['c#', 'unit-testing', 'integration-testing', 'saml', 'okta']",3218,TRUE,4,2
How can we do continuous integration testing of VMs in a VM?,"<p>Most cloud providers grant instances that run in KVM or Xen, which usually or always implies that the owner of the instance doesn't have low-level access to the hypervisor that would be needed in order to create a OS image from scratch, for instance. </p>

<p>This makes me think something like Bochs might be useful for building and testing OS images within a cloud/CI environment, an emulator like <a href=""https://superuser.com/questions/312433/can-you-run-a-machine-emulator-bochs-inside-a-virtual-machine"">Bochs</a> should be able to run within a VM, but would be more slow. Though as an advantage, Bochs would let you test on different hardware, but I don't consider this a requirement at this time.</p>

<p>Is there a somewhat standard solution to this problem? There are many open source distributions and operating systems out there - I'd be interested to know the more elegant approaches taken that might satisfy this requirement (even if they aren't really standard).</p>

<p>Note that containers don't seem like the answer - you may be testing for kernel-specific features in some cases, or even testing a different OS. (However, maybe containers could be useful for instantiating a portable and fast build environment!)</p>
",https://stackoverflow.com/questions/45784544/how-can-we-do-continuous-integration-testing-of-vms-in-a-vm,"['operating-system', 'continuous-integration', 'cloud', 'kvm', 'xen']",89,FALSE,3,0
How to test OnMouseDown function for Integration Testing using Unity Test Tools,"<p>I want to know, how do i test OnMouseDown() function (Or any Event based function) for integration testing using unity test tools.</p>

<p>I attached CallTesting.cs script on cube who will get OnMouseDown() event. I have to test this functionality by using Unity Test Tools(Integration Test Tool). So please give me some guidance how do i achieve this?</p>

<p>Thanks in Advance.</p>
",https://stackoverflow.com/questions/43777031/how-to-test-onmousedown-function-for-integration-testing-using-unity-test-tools,"['unity-game-engine', 'unity-test-tools']",201,FALSE,2,1
Can Spring Boot test classes reuse application context for faster test run?,"<p><code>@ContextConfiguration</code> location attribute does not make sense for Spring Boot integration testing. Is there any other way for reusing application context across multiple test classes annotated with <code>@SpringBootTest</code> ? </p>
",https://stackoverflow.com/questions/44180815/can-spring-boot-test-classes-reuse-application-context-for-faster-test-run,"['java', 'spring', 'spring-boot', 'dependency-injection', 'spring-test']",35154,TRUE,36,5
Use of InSpec with Puppet,"<p>I had been using ServerSpec for my integration testing with Chef.</p>

<p>Since ServerSpec is ""deprecated"" and InSpec is supported by Chef, I've change to use only InSpec, which is also supported in Puppet.</p>

<p><del>However I'm not 100% sure is InSpec is the best tool for integration testing with Puppet. Is there a better or more recommended solution?</del></p>

<p>How can I use inspec with Puppet?</p>
",https://stackoverflow.com/questions/47514602/use-of-inspec-with-puppet,"['integration-testing', 'puppet', 'serverspec', 'inspec']",1112,TRUE,-4,1
Testing Realm in PCL for Xamarin,"<pre><code>RealmConfiguration _configuration = new RealmConfiguration(Path.GetTempFileName());     
var realm = Realm.GetInstance(_configuration);
</code></pre>

<p>Error:</p>

<pre><code>System.TypeInitializationException : The type initializer for 'Realms.Realm' threw an exception.
  ----&gt; System.DllNotFoundException : realm-wrappers
</code></pre>

<p>How do I initialize a realm test database for integration testing in PCL?</p>
",https://stackoverflow.com/questions/45821928/testing-realm-in-pcl-for-xamarin,"['xamarin', 'realm']",274,FALSE,0,1
Integration Test - WebApi - in memory hosting returning 404 error,"<p>We are creating a web api and I am trying to setup integration testing for the web api, so we don't have to use PostMan to verify if it's working. </p>

<p>When I run the webapi and use PostMan, I am getting the expected result. However, when I try to use in memory hosting and run the webapi for integration testing, it is always returning 404. </p>

<p>Using XUnit - the test class is below. </p>

<pre><code>    public class UnitTest1
{
    private readonly TestServer _server;
    private readonly HttpClient _client;

    public UnitTest1()
    {
        var host = new WebHostBuilder()  
            .UseStartup&lt;Startup&gt;();

        this._server = new TestServer(host);
        this._client = _server.CreateClient();
    }

    [Fact]
    public async void TestMethod1()
    {
        var response = await this._client.GetAsync(""api/objects"");
        response.EnsureSuccessStatusCode();

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

        List&lt;obj&gt; result = JsonConvert.DeserializeObject&lt;IEnumerable&lt;obj&gt;&gt;(responseString).ToList();

        Assert.Equal(3, result.Count);
    }
}
</code></pre>

<p>The startup class: </p>

<pre><code>public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

    public void Configure()
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}
</code></pre>

<p>I had to add the configure method in the startup, otherwise test would fail while the class was being initialized. </p>
",https://stackoverflow.com/questions/44332937/integration-test-webapi-in-memory-hosting-returning-404-error,"['asp.net-web-api', 'integration-testing']",789,FALSE,1,1
Integration tests for AspectJ,"<p>I am trying to write Integratation  tests for Custom Aspect. Here is the Aspect Class Snippet.</p>

<pre><code>@Aspect
@Component
public class SampleAspect {

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

   private int count;

   public int getCount(){
      return count;
   }

    public void setCount(){
      this.count= count;
    }


    @Around(""execution(* org.springframework.data.mongodb.core.MongoOperations.*(..)) || execution(* org.springframework.web.client.RestOperations.*(..))"")
    public Object intercept(final ProceedingJoinPoint point) throws Throwable {
        logger.info(""invoked Cutom aspect"");
         setCount(1);
         return point.proceed();

    }

}
</code></pre>

<p>So the above aspect intercepts whenever jointpoint matches the pointcut. Its working fine. But my question is how to perform Integration test.</p>

<p>What I have done is I created the attribute  ""count"" in Aspect for tracking and asserted it in my Junit. I am not sure if this is good or is there a better way of doing integration testing on aspects.</p>

<p>Here is the snippet of Junit what I have done. I presented in bad way but I hope its undestandable of what I have done for Integration testing.</p>

<pre><code>@Test
public void testSamepleAspect(){
   sampleAspect.intercept(mockJointPoint);
   Assert.assertEquals(simpleAspect.getCount(),1);
}
</code></pre>
",https://stackoverflow.com/questions/41446622/integration-tests-for-aspectj,"['java', 'junit', 'mockito', 'integration-testing', 'aspectj']",7515,TRUE,7,2
Http responses are not recorded when using npm replay package?,"<p>I'm trying to use npm replay package to record the http responses while integration testing. I am using chai and mocha. This is my code:</p>

<pre><code>var chai = require('chai');
var bodyParser = require('body-parser');
var supertest = require('supertest');
var express = require('express');
var expect = chai.expect;
var replay  = require('replay');

var assert  = require('assert');
var HTTP    = require('http');
var primary = require('./data/primary.json');

describe('Server Tests', function() {

    beforeEach(function(){
        replay.localhost('127.0.0.1:3978');
    });

    it('should run the replay module', function(done) {
        supertest('http://localhost:3978')
            .post('/api/messages')
            .send(primary)
            .end(function (err, response) {
                console.log(response);
               expect(response.statusCode).to.eq(202);
               //expect(response.body).to.eq(""Oxymoron 2. Exact estimate\n\n[codehappy] http://iheartquotes.com/fortune/show/38021\n"");
                console.log('Woot!');
                done();
            });
    });
});
</code></pre>

<p>Also, I get the correct response status code. </p>
",https://stackoverflow.com/questions/44528163/http-responses-are-not-recorded-when-using-npm-replay-package,"['node.js', 'npm', 'replay']",244,FALSE,1,1
Grails 3.2.9: Spring Rest Docs using Rest Assured giving Payload Handling Exception: com.fasterxml.jackson.core.JSONParseException,"<p>I am trying to integrate Spring Rest docs with Grails 3.2.9 application, using Rest Assured. During integration testing it is producing the Payload Handling Exception.</p>

<p>Full stack trace:  </p>

<pre><code>org.springframework.restdocs.payload.PayloadHandlingException: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('&lt;' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: [B@793cd42d; line: 1, column: 2]
    at org.springframework.restdocs.payload.JsonContentHandler.readContent(JsonContentHandler.java:84)
    at org.springframework.restdocs.payload.JsonContentHandler.findMissingFields(JsonContentHandler.java:50)
    at org.springframework.restdocs.payload.AbstractFieldsSnippet.validateFieldDocumentation(AbstractFieldsSnippet.java:113)
    at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:74)
    at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:64)
    at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:192)
    at org.springframework.restdocs.restassured.RestDocumentationFilter.filter(RestDocumentationFilter.java:63)
    at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:73)
    at org.springframework.restdocs.restassured.RestAssuredRestDocumentationConfigurer.filter(RestAssuredRestDocumentationConfigurer.java:65)
    at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:73)
    at com.jayway.restassured.internal.RequestSpecificationImpl.applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy:1574)
    at com.jayway.restassured.internal.RequestSpecificationImpl.get(RequestSpecificationImpl.groovy:159)
    at so.con.BaseRestDocTestSetup.$tt__createDoc(BaseRestDocTestSetup.groovy:130)
    at so.con.BaseRestDocTestSetup.createDoc_closure4(BaseRestDocTestSetup.groovy)
    at groovy.lang.Closure.call(Closure.java:414)
    at groovy.lang.Closure.call(Closure.java:430)
    at grails.transaction.GrailsTransactionTemplate$1.doInTransaction(GrailsTransactionTemplate.groovy:70)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
    at grails.transaction.GrailsTransactionTemplate.executeAndRollback(GrailsTransactionTemplate.groovy:67)
    at so.con.v1.docs.ConfApiDocSpec.test and document get request for /conf getting conf-list as Response(ConfApiDocSpec.groovy:63)
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('&lt;' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: [B@793cd42d; line: 1, column: 2]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1702)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:558)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:456)
    at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2689)
    at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:878)
    at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:772)
    at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3834)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3783)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2929)
    at org.springframework.restdocs.payload.JsonContentHandler.readContent(JsonContentHandler.java:81)
    ... 19 more
</code></pre>

<p>Please help me resolve this.</p>
",https://stackoverflow.com/questions/44557363/grails-3-2-9-spring-rest-docs-using-rest-assured-giving-payload-handling-except,"['json', 'grails', 'rest-assured', 'asciidoc', 'spring-restdocs']",242,FALSE,0,1
Going back to specific commit,"<p>We are using github model for our projects. ie: developers send pull requests and then we merge that to master. </p>

<p>We do deployment from the <code>master</code> branch. We do code freeze, do regression and integration testing after that via blue green deployment we go live. We dont do any production deployment without regression and integration testing. </p>

<p>Two days ago, we had a problem, client wanted to do a urgent hot fix. Since I dont have a hotfix branch, I need to go back to the last commit of the last deployment. </p>

<p>How can I go back to previous commit at time T and make the changes, commit then forward to the current time?</p>
",https://stackoverflow.com/questions/45648741/going-back-to-specific-commit,['git'],73,TRUE,1,1
Spring boot integration test with multiple data sources getting url cannot be null,"<p>Currently, I am working on spring boot application, we are connecting mysql as part of the main database and H2 Db(in memory) as part of integration testing. Now we have requirement to add two more databases, I am connecting multiple data source by providing multiple data sources in application.properties</p>

<pre><code>spring.mys.datasource.url=jdbc:mysql://17.27.24.33:3306/my-db
spring.mys.datasource.username=root
spring.mys.datasource.password=1234
spring.mys.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.teradata.datasource.url=jdbc:mysql://17.27.24.33:3306/mydb
spring.teradata.datasource.username=root
spring.teradata.datasource.password=password
spring.teradata.datasource.driver-class-name=com.mysql.jdbc.Driver
</code></pre>

<p>and when we are having single data source I am able to connect to HSQL in memory db as part for test application.properties with profile test</p>

<pre><code>spring.jpa.database: HSQL          
spring.jpa.hibernate.ddl-auto=create-drop          
spring.profiles.active=test  
</code></pre>

<p>After adding second data source my integration testing got failed with below error. Basically, we need to implement integration test for both data sources. appreciate any help, thanks.</p>

<p>Our code in the integration test</p>

<pre><code>    @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
    @ContextConfiguration(classes = { ServiceConfig.class, JWTProtectedWebSecurity.class })
    public abstract class BaseIRTest  {
    }
</code></pre>

<p>See the error below while running the maven test</p>

<pre><code>2017-11-22 12:31:04.479 ERROR 14648 --- [           main] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

java.sql.SQLException: The url cannot be null
    at java.sql.DriverManager.getConnection(DriverManager.java:649) ~[na:1.8.0_60]
    at java.sql.DriverManager.getConnection(DriverManager.java:208) ~[na:1.8.0_60]
    at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:308) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:203) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:732) [tomcat-jdbc-8.5.11.jar:na]
    at 
</code></pre>
",https://stackoverflow.com/questions/47430852/spring-boot-integration-test-with-multiple-data-sources-getting-url-cannot-be-nu,['spring-boot'],1266,FALSE,0,0
What is Subsytem Testing for software testing,"<p>What exactly is Subsystem testing and is it any different from Integration Testing? Is subsystem testing just testing that the methods work when the parameters are passed to them?</p>

<p>What would be a good subsystem test for this code </p>

<pre><code>package server.controller;
import server.storage.ParkedUsers;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeSet;
import server.storage.ParkingSpot;

/**
 * This is the server class that controls all data access and flow.
 * It is also responsible of creating all the parking user objects
 * once it searches them in the FIU Database.
 */
public class AccessControlServer extends Thread
{
    private static ParkedUsers garage = ParkedUsers.instance(""garage.txt"");
    private final int portNum;
    private PrintWriter sout = null;
    private HashMap&lt;String, PrintWriter&gt; displayConnections 
                                    = new HashMap&lt;String, PrintWriter&gt;();

    /**
     * constructor that initializes the port number variable
     * @param p integer that contains the port number 
     * to which this server will listen to
     */
    public AccessControlServer(int p)
    {
        portNum = p;
        mapConnections();
    }
    /**
     * helper method that maps the text file into the hashmap
     */
    private void mapConnections()
    {

        sout = null;
        displayConnections.put(""security"", sout);
        for(TreeSet&lt;ParkingSpot&gt; t: garage.values())
            for(ParkingSpot p: t)
            {
                displayConnections.put(p.getParkingNumber(), 
                        p.getPrintWriter());
            }
    }

    @Override
    public void run()
    {
        try
        {
            startServer();
        }
        catch(IOException e)
        {
            System.out.println(""Can't listen on port "" + portNum);
        }
    }

    /**
     * initializes the server with the specified port number and 
     * starts listening for connections
     * @throws IOException exception thrown if there is a problem 
     * with the server
     */
    public void startServer() throws IOException
    {
        ServerSocket ss = new ServerSocket(portNum);
        while(true)
        {
            Socket s = ss.accept();
            Thread t = new Thread(new ConnectionHandler(s));
            t.start();
        }
    }    

    /**
     * method to send a message to a client
     * @param msg sends a string message to the specified client
     * @param pout the print writer connection to the client
     */
    public void sendMessage(String msg, PrintWriter pout)
    {        
        pout.println(msg);
    }

    /**
     * send the security display the status of all the parking spots
     */
    public void sendStatus()
    {
        ArrayList&lt;String&gt; stat = garage.getStatus();
        for(int i = 0;i &lt; stat.size(); i++)
            sendMessage(stat.get(i), sout);
    }

    /**
     * method called to reserve a spot for the user
     * @param spot the spot to be reserved by the user
     * @param id the ID of the user reserving the spot
     */
    synchronized public void reserveSpot(ParkingSpot spot, String id)
    {
        PrintWriter pout = displayConnections.get(spot.getParkingNumber());
        sendMessage(""reserve"", pout);
        sendMessage(id, pout);
    }
    /**
     * sends the message to the security display that an
     * user has parked on the wrong spot
     * @param msg the message to be sent
     */
    synchronized void wrongUserDetected(String msg)
    {
        if(sout == null)
            return;
        sendMessage(""wrong"", sout);
        sendMessage(msg, sout);
    }

    /**
     * sends the message to the security display that a 
     * duplicate ID was detected
     * @param msg the message to be sent
     */
    synchronized void duplicateIdFound(String msg, String msg2)
    {
        if(sout == null)
            return;
        sendMessage(""duplicate"", sout);
        sendMessage(msg, sout);
        sendMessage(msg2, sout);
    }


    /**
     * adds the client to the hashmap containing all the connections
     * @param key the key of the hashmap
     * @param out the print writer connection of the server to the client
     * @param spot the parking spot of the corresponding display
     */
    synchronized private void addDisplay(String key, PrintWriter out, 
            ParkingSpot spot)
    {
        if(!displayConnections.containsKey(key))
            System.out.println( ""Invalid spot number."");
        else 
        {
            displayConnections.put(key, out);
            System.out.println( ""Connected display to spot successfully."");
            spot.setPrintWriter(out);
        }
    }

    /**
     * removes the display from the hashmap containing all the connections
     * @param key the key of the hashmap
     * @param spot the parking spot of the corresponding display
     */
    synchronized private void removeDisplay(String key, ParkingSpot spot)
    {
        displayConnections.put(key, null);
        spot.setPrintWriter(null);
    } 

    /**
     * accessor
     * @param key the clients spot number
     * @return iff the connection is still alive with the client
     */
    public boolean isConnectionAvailable(String key)
    {
        return (displayConnections.get(key) == null);
    }
    /**
     * private class that handles each connection on a separate thread.
     */
    private class ConnectionHandler implements Runnable
    {
        /*
         * constructor of the private class
         */
        public ConnectionHandler(Socket sock)
        {
            theSocket = sock;
        }

        @Override
        public void run()
        {
            PrintWriter pout = null;
            String spotNumber = """";
            try
            {
                InputStream in = theSocket.getInputStream();
                OutputStream out = theSocket.getOutputStream();

                Scanner scan = new Scanner(in);
                pout = new PrintWriter(out, true);

                spotNumber = scan.nextLine();

                System.out.println(spotNumber);

                if(spotNumber.equalsIgnoreCase(""security""))
                    runSecurityDisplay(scan, pout);
                else if(displayConnections.containsKey(spotNumber))
                    runParkingDisplay(scan, pout, spotNumber);


            }

            catch( IOException e )
            {
                System.out.println( ""Socket error: "" + e + "" "" +
                                    theSocket.getRemoteSocketAddress( ) );
            }
            finally
            {   
                //removes the display from the list
                removeDisplay(spot.getParkingNumber(), spot);  
                try
                {
                    if( theSocket != null )
                        theSocket.close( );                    
                }
                catch( IOException e )
                {
                    System.out.println( ""Socket error: "" + e + "" "" +
                                    theSocket.getRemoteSocketAddress( ) );
                }

            }
        }

        /*
         * runs the thread for the security display client
         */
        private void runSecurityDisplay(Scanner scan, PrintWriter pout)
        {
            if(sout != null)
            {
                sendMessage(""another"", pout);
                return;
            }
            sout = pout;
            sout.println(""successful connection!"");

            while(theSocket.isConnected())
            {
                if(theSocket.isClosed())
                    break;
                try 
                {
                    Thread.sleep(2000);
                } 
                catch (InterruptedException e) 
                {
                    System.out.println(e);
                }
                sendStatus();
            }

            sout = null;
            displayConnections.put(""security"", null);




        }
        /**
         * runs the displays threads for each of the parking display clients
         */
        private void runParkingDisplay(Scanner scan, PrintWriter pout, 
                String spotNumber)
        {

            spot = garage.searchBySpotNumber(spotNumber);

            if(!isConnectionAvailable(spotNumber))
            {
                System.out.println(""Another display is connected to  spot #"" 
                                    + spotNumber);
                sendMessage(""another"", pout);
                return;
            }

            addDisplay(spotNumber, pout, spot);
            sendMessage(spot.getParkingType(), pout);
            boolean correct = true;
            while(scan.hasNextLine())
            {
                String oneLine = scan.nextLine();

                if(oneLine.equals(""leave""))
                {
                    if(correct)
                        spot.removeAssignedUser();
                    else
                        correct = true;
                }

                else if(oneLine.equals(""wrong""))
                {
                    wrongUserDetected(""Wrong user detected on parking spot #"" 
                            + spot.getParkingNumber());
                    if(spot.isAvailable())
                    {
                        ParkingUser user = new GuestUser();
                        spot.assignParkingSpot(user);
                    }
                    else
                        correct = false;
                }
            }


        }        
        private ParkingSpot spot;
        private Socket theSocket;
    }
}
</code></pre>
",https://stackoverflow.com/questions/42471751/what-is-subsytem-testing-for-software-testing,"['junit', 'mocking', 'mockito']",126,FALSE,0,1
"How to send integration test results, if analysis results have already been transmitted?","<p>I have an integration testing stage in our pipeline. This stage does not immediately run after the build and the unit-tests.</p>

<p>How can I send the integration test results to SonarQube, if the Sonar Analyzer results have already been transmitted?</p>
",https://stackoverflow.com/questions/47523145/how-to-send-integration-test-results-if-analysis-results-have-already-been-tran,"['c#', '.net', 'sonarqube']",55,FALSE,0,0
Does Citrus Framework for Integration testing(Java) supports Object to Object Asserts as in Junit?,"<p>I am working on Citrus Integration Testing for a Web-service. I need to use the same DB used by the application. I am wondering if I can get response in Citrus in form of Objects, so that I can use the Object in Assert.</p>
",https://stackoverflow.com/questions/42198495/does-citrus-framework-for-integration-testingjava-supports-object-to-object-as,['citrus-framework'],228,TRUE,0,1
Dual database for Java Spring Integration JUnit test,"<p>Currently I'm using H2 database for Junit integration testing with Spring Data, its working fine but I configured one more database with Junit test. But now it doesn't work. Please help me to resolve this.</p>

<p>I try to configure the additional database for quartz schedulers.</p>
",https://stackoverflow.com/questions/44906118/dual-database-for-java-spring-integration-junit-test,"['java', 'junit', 'spring-data-jpa', 'integration-testing', 'quartz-scheduler']",388,FALSE,0,1
View data of H2 database during @DataJpaTest cases,"<p>I am learning spring-boot test and find <a href=""http://www.baeldung.com/spring-boot-testing"" rel=""nofollow noreferrer"">this article</a>,</p>

<blockquote>
  <p>4.Integration Testing with @DataJpaTest</p>
</blockquote>

<p>How can I view the content of h2 database using the info below by configuring client tool such as intellij-idea's Tool > Database.</p>

<p>Or is there any better way to peek those information.</p>

<p><code>INFO 11276 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:h2:mem:094de3b8-72c0-4740-bdf6-5ae1a36ad9f4;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'</code></p>
",https://stackoverflow.com/questions/45659324/view-data-of-h2-database-during-datajpatest-cases,"['spring-boot', 'intellij-idea', 'spring-data-jpa', 'h2', 'embedded-database']",2081,FALSE,3,1
Mock Rest Server Response for Unit Testing,"<p>In integration testing, I use a real remote server to consume REST APIs. 
What's the simplest way to provide those responses within a unit test w/o depending on external entity. </p>

<p>One possible approach is to build </p>

<pre><code>public class TestHttpResponse implements   org.apache.http.client.methods.CloseableHttpResponse

override

 @Override
    public StatusLine getStatusLine() {
      return new StatusLine() {
        @Override
        public ProtocolVersion getProtocolVersion() {
          return null;
        }

        @Override
        public int getStatusCode() {
          return statusCode;
        }

        @Override
        public String getReasonPhrase() {
          return reasonPhrase;
        }
      };
    }
   ...
</code></pre>

<p>Is there a simpler and better way for mocking REST API response payloads?</p>
",https://stackoverflow.com/questions/43350697/mock-rest-server-response-for-unit-testing,"['rest', 'unit-testing', 'mockrestserviceserver']",1430,TRUE,2,1
.net core ef migration testing - apply migrations using c# method,"<p>I think that ef migrations must be tested.
As for me integration testing will be best solution.
Current solution is to apply migrations to in memory database, but problem is that i want to run down scripts of migration also.</p>

<p>Do yoy know how to apply migrations using c# code?</p>
",https://stackoverflow.com/questions/41664434/net-core-ef-migration-testing-apply-migrations-using-c-method,"['.net-core', 'entity-framework-core', 'entity-framework-migrations']",2732,TRUE,2,3
How to run a docker container for integration testing a Spring Boot app within VSTS,"<p>The problem is how to run a Docker database image within VSTS and then run a Maven task to package a Spring Boot application.</p>

<p>The goal is to be able to perform integration testing with a real database that can be destroyed after the build has been completed.</p>
",https://stackoverflow.com/questions/47197393/how-to-run-a-docker-container-for-integration-testing-a-spring-boot-app-within-v,"['docker', 'spring-boot', 'azure-devops', 'azure-pipelines']",1119,TRUE,0,2
Conditional nosetests from bash,"<p>I'm attempting to only run tests in files that have changed between git commits as part of our integration testing in Jenkins.</p>

<p>The code below works, <em>unless</em> the filters remove all file results.  Then ALL tests get run by nose.  I would want no tests run in that case.</p>

<pre><code>if [ $GIT_PREVIOUS_SUCCESSFUL_COMMIT != $GIT_COMMIT ]; then
    git diff --name-only --diff-filter=d $GIT_PREVIOUS_SUCCESSFUL_COMMIT $GIT_COMMIT | grep .py | xargs nosetests -vv
fi
</code></pre>

<p>Any suggestions?</p>
",https://stackoverflow.com/questions/42490437/conditional-nosetests-from-bash,"['bash', 'jenkins', 'nose']",219,TRUE,0,2
How to get registered services in integration test,"<p>I want to add an ApplicationUser user in my integration test, so i need to use ‘UserManager.CreateAsync()’.
I already know how to get the ApplicationDbContext, from the ‘integration testing’ docs page.</p>

<p>My question is how do i get the UserManager service in the integration test or any other di registered service?</p>
",https://stackoverflow.com/questions/46744613/how-to-get-registered-services-in-integration-test,"['dependency-injection', 'asp.net-core', 'integration-testing']",551,TRUE,0,1
How do I write an integration test(C++) using Catch?,"<p>I do know that Catch is a unit testing framework. I have a server(C++) and a client(C++) to test. Is this integration testing? I am testing done functionalities in the server and some in the client that I want to test. Can I use CppUnit?
It is written in Windows.</p>
",https://stackoverflow.com/questions/42793008/how-do-i-write-an-integration-testc-using-catch,"['c++', 'windows', 'unit-testing', 'testing', 'integration-testing']",638,FALSE,-1,1
How to delete an application from IBM UrbanCode Deploy using REST API?,"<p>As part of some integration testing we are creating a uDeploy application, checking it exists and then hoping to delete it after to cleanup.</p>

<p>Looking at the documentation here: <a href=""https://www.ibm.com/support/knowledgecenter/en/SS4GSP_6.2.2/com.ibm.udeploy.api.doc/topics/rest_cli_application.html"" rel=""nofollow noreferrer"">https://www.ibm.com/support/knowledgecenter/en/SS4GSP_6.2.2/com.ibm.udeploy.api.doc/topics/rest_cli_application.html</a> and googling around, I can't find an API endpoint to delete the created application.</p>

<p>Any help?</p>
",https://stackoverflow.com/questions/46643544/how-to-delete-an-application-from-ibm-urbancode-deploy-using-rest-api,"['rest', 'urbancode', 'udeploy']",511,TRUE,1,1
How to properly test Spring @Transactional timeout,"<p>I got a simple API loading data from a <code>PostgreSQL</code> database and a simple CRUD service/repository (all spring-boot based). I've marked my create/update methods in the service layer as:</p>

<pre><code>@Transactional(timeout=5)
public void create(Entity x){
   ... 
   repository.save(x) 
}
</code></pre>

<p>How can I test (integration testing, by the way) the condition under the timeout exception would be thrown? My repository is an extension of <code>CrudRepository</code>.</p>

<p>Something like <code>doTimeout(6000).when(repository).save(...)</code></p>
",https://stackoverflow.com/questions/47930369/how-to-properly-test-spring-transactional-timeout,"['spring', 'spring-boot', 'spring-data-jpa', 'transactional']",871,FALSE,2,1
What project for Integration Tests in Visual Studio?,"<p>I have a pretty simple question: What kind of project should I create for <code>Integration Tests</code> in Visual Studio? The only proposed project type under <code>Test</code> tab in <code>Visual C#</code> is <code>Unit Test Project</code>, but it's not integration test, so I'm not sure </p>

<p>This is what I read, but couldn't find an answer :</p>

<p><a href=""https://stackoverflow.com/questions/32060452/integration-testing-in-visual-studio-with-different-project-types"">Integration Testing In Visual Studio With Different Project Types</a></p>

<p><a href=""https://stackoverflow.com/questions/1894339/how-do-you-separate-unit-tests-from-integration-tests-in-visual-studio"">How do you separate unit tests from integration tests in Visual Studio?</a></p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/44826725/what-project-for-integration-tests-in-visual-studio,"['visual-studio', 'integration-testing']",4956,TRUE,8,1
Boot kernel testing,"<p>Has anyone written a test plan for a boot ROM?</p>

<p>This boot ROM will just boot the device from flash or a host via SPI</p>

<p>This will be used in an embedded system with cortex M3 and data acquisition from sensors</p>

<p>Do you modify the boot rom code for unit/integration testing?</p>

<p>Thanks a lot</p>
",https://stackoverflow.com/questions/46837142/boot-kernel-testing,"['unit-testing', 'kernel', 'boot']",39,FALSE,-2,1
Running Nunit Test in Administrator Mode,"<p>I am currently using VS 2015 professional and using Nunit Framework for unit testing. </p>

<p>I am using the same framework for integration testing as well. While doing so I realized, one of the <code>.dll</code> supplied by the hardware manufacturer requires Administrator Privileges for it to be used in an application or tests(my current issue lies here) I did some research and tried a few things mentioned below to use the <code>dll</code> in admin mode. </p>

<p><strong>1</strong> So I started the Visual Studio in Administrator mode for the test to run, but still the <code>dll</code> (functions) do not work. (running test in VS debug mode)</p>

<p><strong>2</strong> I just used normal debug without Nunit framework, then the <code>dll</code> worked.</p>

<p>My conclusion --> I think that the Nunit somehow is not elevated to Admin.</p>

<p>Questions and Problem</p>

<p>I need to use the dll in Admin mode for the integration testing(where i use Nunit Framework)</p>

<ol>
<li>Is it possible to do so?</li>
<li>If no, then why and if yes, then how</li>
</ol>

<p>Please provide your input</p>
",https://stackoverflow.com/questions/44537606/running-nunit-test-in-administrator-mode,"['c#', 'nunit', 'administrator']",771,FALSE,2,0
Logging into application with RSpec,"<p>I am trying to test a controller that has authenticated routes. I'm using OmniAuth with Google OAuth2.0. I followed <a href=""https://github.com/omniauth/omniauth/wiki/Integration-Testing"" rel=""nofollow noreferrer"">this guide</a> on the OmniAuth wiki to set it up for integration testing. However, my test is failing with the following error:</p>

<pre><code>1) GroupsController GET #show when user logged in responds with HTTP 200 and a group object
     Failure/Error: expect(response).to have_http_status(200)
       expected the response to have status code 200 but it was 302
     # ./spec/controllers/groups_controller_spec.rb:27:in `block (4 levels) in &lt;top (required)&gt;'
</code></pre>

<p>suggesting that the request is still being redirected.</p>

<p>I've put all the relevant files in <a href=""https://gist.github.com/Carpetfizz/5dad0f0f8d5abe79cbe39d6d226cd5e0"" rel=""nofollow noreferrer"">this Gist</a></p>
",https://stackoverflow.com/questions/41472663/logging-into-application-with-rspec,"['ruby-on-rails', 'rspec', 'oauth', 'omniauth']",98,TRUE,0,1
OPA5: Purpose of &quot;and&quot; in promise returned from waitFor,"<p>I'm kind of new to integration testing with OPA5, so I was reading a <a href=""https://openui5.hana.ondemand.com/#docs/guide/10592affce3e4f1ba73c3125ee06e0b7.html"" rel=""nofollow noreferrer"">tutorial on the dev guide</a>. There is this <code>and</code> included before <code>iTeardownMyAppFrame()</code> in the first sample code.</p>

<blockquote>
<pre><code>// Assertions
Then.onThePostPage.theTitleShouldDisplayTheName(""Jeans"").and.iTeardownMyAppFrame();
</code></pre>
</blockquote>

<p>I was wondering what <code>and</code> exactly does but I couldn't find any documentation about it. The <code>and</code> property is included in the promise returned from the <a href=""https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.test.Opa5.html#waitFor"" rel=""nofollow noreferrer""><code>waitFor</code></a> method of <code>sap.ui.test.Opa5</code>, as the image below shows:</p>

<p><a href=""https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.test.Opa5.html#waitFor"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/grzk8.gif"" alt=""enter image description here""></a></p>

<p>From API reference:</p>

<blockquote>
  <p>{jQuery.promise} A promise that gets resolved on success</p>
</blockquote>

<p>So I looked at the <a href=""https://api.jquery.com/category/deferred-object/"" rel=""nofollow noreferrer"">jQuery documentation</a> about the promise but I couldn't find anything about <code>and</code> there either which indicates that the returned jQuery.promise is extended by OPA5.</p>

<p><code>iTeardownMyAppFrame</code> <strong>without</strong> <code>and</code> worked fine as I assumed (since it always returns the same promise). So what is the purpose of <code>and</code>? Is it just syntactic sugar? Did someone experience errors because of the missing <code>and</code>? Is there any documentation about it that I overlooked?</p>

<hr>

<p>PS: Let me know if you need a minimal example of integration testing with OPA5.</p>
",https://stackoverflow.com/questions/42393072/opa5-purpose-of-and-in-promise-returned-from-waitfor,"['jquery', 'integration-testing', 'sapui5']",452,TRUE,1,2
Rails check if variable differs from record,"<p>I want to see if my variable differs from the corresponding record in the database.I am aware of <a href=""http://api.rubyonrails.org/classes/ActiveModel/Dirty.html"" rel=""nofollow noreferrer"">'attribute'_changed? method</a>, but it only works if you updated the record through the variable. </p>

<p>Example</p>

<pre><code>user = User.first # name = bar
u.update(name: ""foo"")
u.name_changed? # =&gt; true
</code></pre>

<p>however, in this case (integration testing for example)</p>

<pre><code>u = User.first # name = bar
User.first.update(name: ""foo"")
u.name # =&gt; 'bar'
u.name_changed? #false
u.reload
u.name_changed #false
</code></pre>

<p>I want to check if my variable <em>u</em> differs from User.first in some attribute, which wasn't change through it.</p>
",https://stackoverflow.com/questions/43018501/rails-check-if-variable-differs-from-record,"['ruby-on-rails', 'ruby', 'activerecord']",106,TRUE,0,1
Testing Spring Boot application with Spring Security using Spock,"<p>I am trying to do integration testing on Spring Boot application with Spring Security. </p>

<pre><code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationSpec extends Specification{

    @Autowired
    TestRestTemplate testRestTemplate

    def setup() {
        BasicAuthorizationInterceptor bai = new BasicAuthorizationInterceptor(""username"", ""password"")
        testRestTemplate.getRestTemplate().getInterceptors().add(bai)
    }
</code></pre>

<p>All the dependencies are there and TestRestTemplate gets injected. Problem is when I try to test POST endpoint. I get following error: </p>

<blockquote>
  <p>Could not verify the provided CSRF token because your session was not
  found.</p>
</blockquote>

<p>How do I get valid CSRF token and suply it to my TestRestTemplate?</p>
",https://stackoverflow.com/questions/44029437/testing-spring-boot-application-with-spring-security-using-spock,"['java', 'spring', 'spring-mvc', 'spring-security', 'spock']",583,FALSE,0,0
sbt 1.0 simultaneously run and test,"<p>Pre 1.0 I ran a Main method in one instance of sbt and did integration testing against it in another instance of sbt. With 1.0 I get server already running errors. Do I now have to run the Main outside sbt or is there a 1.0 way to test while running?</p>

<p>Thanks, <a href=""https://stackoverflow.com/users/736957/laughedelic"">laughedelic</a> bgRun should be more prominent in the docs</p>
",https://stackoverflow.com/questions/47482195/sbt-1-0-simultaneously-run-and-test,['sbt'],149,TRUE,0,1
How to run asp.net core api and unit test in the same solution,"<p>I have a project solution where I have my ASP.NET Core Web Api and Unit test project.</p>

<p>I'm confused how to run integration testing for my web api having those projects in the same solution. I tried selecting multiple startup projects in the settings but what it does is run the api project and console app then closes again.</p>

<p>Any idea about how to do this?</p>
",https://stackoverflow.com/questions/45801050/how-to-run-asp-net-core-api-and-unit-test-in-the-same-solution,"['unit-testing', 'asp.net-core']",82,FALSE,1,0
Why is TestServer not able to find controllers when controller is in separate assembly for asp.net core app?,"<p>For some reason, when ASP.NET core controllers are created in separate assembly, the TestServer is not able to find controller actions when the client makes a request.(results in 404 response) Why is this? How can I work around it?
Here are steps to reproduce.  </p>

<ol>
<li>Create new ASP.NET Core WebAPI using .NET core</li>
<li>Create integration tests in separate project and configure the test to use TestServer() client and get tests to work successfully. </li>
<li>Now, separate the controller into its own shared library and refactor project created in step 1 to use this shared library instead. </li>
<li>Re-run test which contains the TestServer() class. You'll notice now it fails.</li>
</ol>

<p>See the follwing link for creating the integration tests. <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""noreferrer"">Integration testing w/ ASP.NET Core</a></p>
",https://stackoverflow.com/questions/43669633/why-is-testserver-not-able-to-find-controllers-when-controller-is-in-separate-as,"['c#', 'unit-testing', 'asp.net-web-api', 'asp.net-core', 'asp.net-core-mvc']",13042,TRUE,40,4
Stubbing a method of tested class with Minitest,"<p>I am writing a part of larger framework and I have problems with stubbing. Here is what I have </p>

<pre><code>class A
    def bar
        # some code
        foo
        # some code
    end
    def foo
        # method dependent on other parts of the framework
    end
end
</code></pre>

<p>Now I want to test the method bar, but it depends on foo and foo calls other parts of the framework (which is more a matter of integration testing). What I would like to do is to stub foo in my test, something like:</p>

<pre><code>class TestA &lt; Minitest::Test
    def stubbed_foo
        return 5
    end
    def test_bar
        a = A.new
        # use stubbed_foo in a instead of foo
        result = a.bar 
        # some assert
    end
end
</code></pre>

<p>But I don't know how to do it.</p>
",https://stackoverflow.com/questions/42952789/stubbing-a-method-of-tested-class-with-minitest,"['ruby', 'minitest']",208,TRUE,1,1
WLST disconnect command issue,"<p>I had ran <code>wlst.cmd</code> in my local system after I ran my Weblogic Admin Instance. But as WLST is stateful, I am getting connected to my IT env which is my Integration Testing environment (some UNIX machine for my project). I tried <code>disconnect()</code> to goto offline mode, however it is failed.</p>

<pre><code>wls:/beaProjDir/serverConfig&gt; disconnect()

You will need to be connected to a running server to execute this command
</code></pre>

<p>Please help to go offline mode in WLST. As I need to get some work done in my local system.</p>
",https://stackoverflow.com/questions/41607148/wlst-disconnect-command-issue,"['python', 'weblogic', 'wlst']",462,FALSE,0,1
Jenkins Continues Integration setup for Scala Maven project,"<p>We have started working on developing a Spark-Scala Maven project.We are a team of 6 developers commit code to git repository. We use Intellij IDE and codehup repository using GIT . Need to setup Jenkins for Continues integration testing and build. Could you please some one help me an approach to setup Jenkins or Spark-Scala project, Specifically needs a scala- jenkins in POM.XML? 
Any help is greatly appreciated. </p>
",https://stackoverflow.com/questions/44557886/jenkins-continues-integration-setup-for-scala-maven-project,"['scala', 'maven', 'apache-spark', 'jenkins', 'jenkins-pipeline']",734,FALSE,0,1
Is it possible to enable Spring context caching in Mule FunctionalTestCase?,"<p>I use FunctionalTestCase in order to test Mule ESB 3.5 application.</p>

<p>For testing I have a class which looks like:</p>

<pre><code>public class MyIntegrationTest extends FunctionalTestCase {

    @Override
    protected String getConfigFile()
    {
        return ""app-config.xml"";
    }

    @Test
    public void test1() throws Exception{
    }
    @Test
    public void test2() throws Exception{
    }
    ...
}
</code></pre>

<p>I noticed that every <code>@Test</code> method re-creates application context and tests are fairly slow.</p>

<p>With bare Spring framework simple integration test would cache application context so tests would be much faster. I was wondering is it possible to do Mule application integration testing with cached Spring application context?</p>
",https://stackoverflow.com/questions/47968221/is-it-possible-to-enable-spring-context-caching-in-mule-functionaltestcase,"['spring', 'mule']",56,TRUE,0,1
Way to get Azure Function default key with ARM output or powershell,"<p>I'm attempting to set up integration testing for an Azure Function app. Deployment is going fine, but I need a way to programatically get the default key to run my integration tests.</p>

<p>I've tried what is linked here - <a href=""https://stackoverflow.com/questions/43253453/get-function-host-keys-of-azure-function-in-powershell"">Get Function &amp; Host Keys of Azure Function In Powershell</a> - but cannot get the listsecrets working in my ARM deployment template. Listsecrets is not recognized.</p>

<p>Does anyone know how to get this key with an ARM template and/or powershell?</p>
",https://stackoverflow.com/questions/46736165/way-to-get-azure-function-default-key-with-arm-output-or-powershell,"['powershell', 'azure', 'azure-functions']",1999,TRUE,5,2
test spring 5 reactive rest service,"<p>I'm using SpringBoot 2 and Spring 5 (RC1) to expose reactive REST services. but I can't manage to write unit test for those controllers. </p>

<p>Here is my controller </p>

<pre><code>@Api
@RestController
@RequestMapping(""/"")
public class MyController {

    @Autowired
    private MyService myService;


    @RequestMapping(path = ""/"", method = RequestMethod.GET)
    public Flux&lt;MyModel&gt; getPages(@RequestParam(value = ""id"", required = false) String id,
            @RequestParam(value = ""name"", required = false) String name) throws Exception {

        return myService.getMyModels(id, name);
    }
} 
</code></pre>

<p>myService is calling a database so I would like not to call the real one. (I don't wan't integration testing) </p>

<p>Edit : </p>

<p>I found a way that could match my need but I can't make it work :</p>

<pre><code>@Before
    public void setup() {

        client = WebTestClient.bindToController(MyController.class).build();

    }
@Test
    public void getPages() throws Exception {

        client.get().uri(""/"").exchange().expectStatus().isOk();

    }
</code></pre>

<p>But I'm getting 404, seems it can't find my controller </p>
",https://stackoverflow.com/questions/44529858/test-spring-5-reactive-rest-service,"['spring', 'rest', 'spring-boot', 'reactor']",1305,TRUE,1,1
Verify Backing Bean values using Arquillian Warp,"<p>My goal is to test using Arquillian Warp </p>

<p>1. Already navigated to a JSF page on a previous test</p>

<p>2. On a another test set a text field to a value, using warp i need to inject the ViewScope Bean , and verify the value in the backing bean</p>

<p>Sample Code </p>

<pre><code>@RunWith(Arquillian.class)
@WarpTest
@RunAsClient
public class TestIT {

    private static final String WEBAPP_SRC = ""src/main/webapp"";
    private static final String WEB_INF_SRC = ""src/main/webapp/WEB-INF"";
    private static final String WEB_RESOURCES = ""src/main/webapp/resources"";

    @Deployment(testable = true)
    public static WebArchive createDeployment() {
        File[] files = Maven.resolver().loadPomFromFile(""pom.xml"")
                .importRuntimeDependencies().resolve().withTransitivity().asFile();

        WebArchive war = ShrinkWrap.create(WebArchive.class, ""test.war"")
                .addPackages(true, ""com.mobitill"")
                .addAsWebInfResource(EmptyAsset.INSTANCE, ""beans.xml"")
                .addAsWebInfResource(new File(WEB_INF_SRC, ""template.xhtml""))
                .addAsWebInfResource(new File(WEB_INF_SRC, ""jboss-web.xml""))
                .addAsWebInfResource(new File(WEB_INF_SRC, ""web.xml""))
                .addAsWebResource(new File(WEBAPP_SRC, ""index.xhtml""))
                .addAsWebResource(new File(""src/main/webapp/demo"", ""home.xhtml""), ""demo/home.xhtml"")
                .addAsResource(""test-persistence.xml"", ""META-INF/persistence.xml"")
                .merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class)
                        .importDirectory(WEB_RESOURCES).as(GenericArchive.class), ""resources"")
                .addAsLibraries(files);
        System.out.println(war.toString(true));
        return war;
    }
    @Drone
    private WebDriver browser;
    @ArquillianResource
    private URL deploymentUrl;

    @Test
    @InSequence(1)
    public final void browserTest() throws Exception {
        browser.get(deploymentUrl.toExternalForm() + ""index"");
        guardHttp(loginImage).click();
        Assert.assertEquals(""navigate to home page "", ""https://127.0.0.1:8080/citi/demo/home"", browser.getCurrentUrl());
    }
    @Test
    @InSequence(2)
    public final void homeManagedBean() throws Exception {
        Warp
                .initiate(new Activity() {
                    @Override
                    public void perform() {
                        WebElement txtMerchantEmailAddress = browser.findElement(By.id(""txtMerchantEmailAddress""));
                        txtMerchantEmailAddress.sendKeys(""demouser@yahoo.com"");
                        guardAjax(btnMerchantSave).click();
                    }
                })
                .observe(request().header().containsHeader(""faces-request""))
                .inspect(new Inspection() {
                    private static final long serialVersionUID = 1L;

                    @Inject
                    HomeManagedBean hmb;

                    @ArquillianResource
                    FacesContext facesContext;

                    @BeforePhase(UPDATE_MODEL_VALUES)
                    public void initial_state_havent_changed_yet() {
                        Assert.assertEquals(""email value "", ""demouser@yahoo.com"", hmb.getMerchantEmail());
                    }

                    @AfterPhase(UPDATE_MODEL_VALUES)
                    public void changed_input_value_has_been_applied() {
                        Assert.assertEquals("" email value "", ""demouser@yahoo.com"", hmb.getMerchantEmail());
                    }
                });
    }
}
</code></pre>

<p>the error i keep gettting is</p>

<pre><code>org.jboss.arquillian.warp.impl.client.execution.WarpSynchronizationException: The Warp failed to observe requests or match them with response.

There were no requests matched by observer [containsHeader('faces-request')]

If Warp enriched a wrong request, use observe(...) method to select appropriate request which should be enriched instead.
Otherwise check the server-side log and enable Arquillian debugging mode on both, test and server VM by passing -Darquillian.debug=true.

    at org.jboss.arquillian.warp.impl.client.execution.SynchronizationPoint.awaitResponses(SynchronizationPoint.java:155)
    at org.jboss.arquillian.warp.impl.client.execution.DefaultExecutionSynchronizer.waitForResponse(DefaultExecutionSynchronizer.java:60)
    at org.jboss.arquillian.warp.impl.client.execution.WarpExecutionObserver.awaitResponse(WarpExecutionObserver.java:64)
</code></pre>

<p>any help will be welcomed or an alternative way of validating a jsf viewscope bean during integration testing</p>
",https://stackoverflow.com/questions/45584304/verify-backing-bean-values-using-arquillian-warp,"['jsf-2', 'integration-testing', 'jboss-arquillian', 'wildfly-10']",307,FALSE,1,1
What is the proper way to setup and seed a database with artificial data for integration testing,"<p>Let's say I have 2 tables in a database, one called <code>students</code> and the other called <code>departments</code>. <code>students</code> looks like the following:</p>

<pre><code>department_id, student_id, class, name, age, gender, rank
</code></pre>

<p>and <code>departments</code> looks like:</p>

<pre><code>department_id, department_name, campus_id, number_of_faculty
</code></pre>

<p>I have an API that can query the database and retrieve various information from the 2 tables. For example, I have an end point that can get number of students on each campus by joining the 2 tables. </p>

<p>I want to do integration testing for my API end points. To do that, I spin up a local database, run migration of the database schemas to create the tables, then populate each table with artificial records such that I know exactly what is in the database. But coming up with a good seeding process has proven to be anything but easy. For the simple example I described above, my current approach involves generating multiple distinct records for each column. For example, I need at least 2 campuses (say <code>main</code> and <code>satellite</code>), and 3 departments (say <code>Electrical Engineering</code> and <code>Mathematics</code> for <code>main</code> campus and <code>English</code> for <code>satellite</code> campus). Then I need at least 2 students in each department or 6 students in total. And if I mix in <code>gender</code>, <code>age</code> and <code>rank</code>, you can easily see that the number of artificial records grows exponentially. Coming up with all these artificial records is manual and thus tedious to maintain.</p>

<p>So my question is: what is the proper way to set up and seed database for integration testing in general? </p>
",https://stackoverflow.com/questions/47019694/what-is-the-proper-way-to-setup-and-seed-a-database-with-artificial-data-for-int,"['java', 'api', 'jvm', 'kotlin', 'integration-testing']",4085,TRUE,13,3
Skipping Devise authentication with minitest,"<p>I am adding some tests to my Rails app and I am finding it cumbersome to have to sign in a user each time.  I found this elegant solution:</p>

<p><a href=""http://www.colorfultyping.com/disabling-devise-for-rails-integration-testing/"" rel=""nofollow noreferrer"">http://www.colorfultyping.com/disabling-devise-for-rails-integration-testing/</a></p>

<p>but it seems to only apply to Rspec. and I can't seem to make that work in Minitest.</p>

<p>Ideally the solution is like above - disable for all tests then you can enable it back for individual tests.</p>
",https://stackoverflow.com/questions/42737982/skipping-devise-authentication-with-minitest,"['ruby-on-rails', 'unit-testing', 'devise', 'minitest']",81,FALSE,0,0
Wiremock custom request matcher in Spring Cloud Contract,"<p>I have been using wiremock for integration testing and I have custom request matcher created and used for authorization stubs. </p>

<p>Is there any way I can use this matcher in spring cloud contract contract definitions? </p>

<p>To be specific - I want to create stub for specific user and the only way I can get user is by decoding authorization token. If decoded token matches a user - I want to match request and use provided stub. </p>
",https://stackoverflow.com/questions/45297012/wiremock-custom-request-matcher-in-spring-cloud-contract,"['wiremock', 'spring-cloud-contract']",654,TRUE,0,1
Automated tests on contracts between microservices?,"<p>Say we have a CreditCardService microservice that depends on a ThreeDSecureService microservice, communicating using JSON.</p>

<p>Minor changes in the API (or even implementation) of the ThreeDSecureService could silently break the CreditCardService (and other potential clients). So, we would like automated tests.</p>

<p>I see two flawed approaches, and am wondering how to improve.</p>

<ol>
<li>Integration testing in ThreeDSecureService.Tests.</li>
</ol>

<p>The accompanying test project of ThreeDSecureService could have an integration test with a fixed JSON input. Faking out any dependencies, it could run an otherwise complete call for that input, confirming that the service swallows the input.</p>

<p>The problem here is that if someone fails to realize how their changes could break clients, they are almost as likely to 'fix' the tests to match their changes.</p>

<ol start=""2"">
<li>Integration testing in CreditCardService.Tests.</li>
</ol>

<p>The <em>client</em> is the one that actually wants to test assertions about ThreeDSecureService's expected input. However, that would require the client solution to include the ThreeDSecureService project, as well as any projects it depends on. This would negate many of the advantages we get from using microservices!</p>

<p><strong>How do we make assertions from the client (safeguarding the dependency) without breaking the loose coupling we get from using microservices?</strong></p>
",https://stackoverflow.com/questions/45751211/automated-tests-on-contracts-between-microservices,"['c#', 'api', 'integration-testing', 'microservices', 'contract']",527,TRUE,1,2
IIS CLI generate applicationhost.config with site for my project,"<p>I have a C# solution with several projects, one of which is a web server run by IIS. I have set <code>&lt;UseGlobalApplicationHostFile&gt;True&lt;/UseGlobalApplicationHostFile&gt;</code> in the csproj file of that project.</p>

<p>When I open Visual Studio, it generates this in ~/Documents/IISExpress/config/applicationhost.config:</p>

<pre><code>    &lt;sites&gt;
        &lt;site name=""WebSite1"" id=""1"" serverAutoStart=""true""&gt;
            &lt;application path=""/""&gt;
                &lt;virtualDirectory path=""/"" physicalPath=""%IIS_SITES_HOME%\WebSite1"" /&gt;
            &lt;/application&gt;
            &lt;bindings&gt;
                &lt;binding protocol=""http"" bindingInformation="":8080:localhost"" /&gt;
            &lt;/bindings&gt;
        &lt;/site&gt;
        &lt;site name=""SealingService"" id=""2""&gt;
            &lt;application path=""/"" applicationPool=""Clr4IntegratedAppPool""&gt;
                &lt;virtualDirectory path=""/"" physicalPath=""C:\Users\sehch\Documents\Paragon\ParagonCore\servers\SealingService\SealingService"" /&gt;
            &lt;/application&gt;
            &lt;bindings&gt;
                &lt;binding protocol=""http"" bindingInformation=""*:61800:localhost"" /&gt;
                &lt;binding protocol=""https"" bindingInformation=""*:44300:localhost"" /&gt;
            &lt;/bindings&gt;
        &lt;/site&gt;
        &lt;siteDefaults&gt;
            &lt;logFile logFormat=""W3C"" directory=""%IIS_USER_HOME%\Logs"" /&gt;
            &lt;traceFailedRequestsLogging directory=""%IIS_USER_HOME%\TraceLogFiles"" enabled=""true"" maxLogFileSizeKB=""1024"" /&gt;
        &lt;/siteDefaults&gt;
        &lt;applicationDefaults applicationPool=""Clr4IntegratedAppPool"" /&gt;
        &lt;virtualDirectoryDefaults allowSubDirConfig=""true"" /&gt;
    &lt;/sites&gt;
</code></pre>

<p>I want to be able to run my project with IIS Express from the command line (for build server integration testing purposes). How can I generate the <code>SealingService</code> site section of applicationhost.config from the command line (without opening Visual Studio)?</p>

<p>I have tried running </p>

<pre><code>""C:\Program Files (x86)\IIS Express\iisexpress.exe""
</code></pre>

<p>in my solution folder, but it only generates the <code>WebSite1</code> section.</p>
",https://stackoverflow.com/questions/45640323/iis-cli-generate-applicationhost-config-with-site-for-my-project,"['c#', 'asp.net', 'visual-studio', 'iis', 'visual-studio-2017']",1749,TRUE,11,1
Unit testing and mocking with RedBean ORM?,"<p>How would I go about unit testing when using RedBean ORM? It uses static methods (<code>R::dispense()</code>, <code>R::store()</code>, etc.) so how can I create a mock object? </p>

<p>Or should I just forget about that idea and simply use a test database which gets <code>nuke()</code>'d at the beginning of each test suite? I'm new to both RedBean and unit testing, but something doesn't sound right about that approach... wouldn't it be on the border of integration testing if I'm using a real database?</p>
",https://stackoverflow.com/questions/41826343/unit-testing-and-mocking-with-redbean-orm,"['unit-testing', 'testing', 'phpunit', 'integration-testing', 'redbean']",84,FALSE,2,0
@DataMongoTest is creating a null MongoTemplate,"<p>I have been trying to follow the instructions in the link below to try to add an automatically configured Embedded MongoDB Instance for Cucumber Integration testing. This is currently not working, since the I keep getting a null MongoTemplate. I thought that @DataMongoTest would automatically configure  ""@Autowired private MongoTemplate mongoTemplate;"" Is this not the case? Below is my code:</p>

<p>mongoTemplate.save(doc, collection); throws a nullpointer exception.</p>

<pre><code>@SpringBootTest(classes = AppCommentApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DataMongoTest
public abstract class SpringIntegrationTest {

    @Value(""${local.server.port}"")
    public int port;

    @Autowired
    private MongoTemplate mongoTemplate;

    protected void importJSON(String collection, String file) {
        try {
            for (String line : FileUtils.readLines(new File(file), ""utf8"")) {
                Document doc = Document.parse(line);
                mongoTemplate.save(doc, collection);
            }
        } catch (IOException e) {
            throw new RuntimeException(""Could not import file: "" + file, e);
        }
    }

}


@RunWith(Cucumber.class)
@CucumberOptions(format = ""pretty"",
                 features = ""src/test/resources/features"",
                 glue = ""com.app.comment.cucumber"")
public class CucumberIntegrationTest {
}


public class StepDefinitions extends SpringIntegrationTest {

    private Map&lt;String, String&gt; headerMap = null;
    private String postBody = null;
    private String putBody = null;
    private String formData = null;
    private Response response = null;
    private String data = null;

    private final static String MONGODB_COLLECTION = ""comment"";
    private final static String MONGODB_DATA = ""src/test/resources/mongodb-data/data.txt"";

    @Before
    public void setup() {
        importJSON(MONGODB_COLLECTION, MONGODB_DATA);
    }

    @Given(""^the header information$"")
    public void the_header_information(Map&lt;String, String&gt; headerMap) throws Throwable {
        this.headerMap = headerMap;
    }

    @Given(""^post message body \""(.*?)\""$"")
    public void post_message_body(String postBody) throws Throwable {
        this.postBody = postBody;
    }

    @Given(""^put message body \""(.*?)\""$"")
    public void put_message_body(String putBody) throws Throwable {
        this.putBody = putBody;
    }
}
</code></pre>

<p>pom.xml file:</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;groupId&gt;com.app.comment&lt;/groupId&gt;
    &lt;artifactId&gt;app-comment-api&lt;/artifactId&gt;
    &lt;version&gt;1.0.4&lt;/version&gt;
    &lt;packaging&gt;jar&lt;/packaging&gt;

    &lt;name&gt;app-comment-api&lt;/name&gt;
    &lt;description&gt;App Comments Microservice&lt;/description&gt;

    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;1.5.1.RELEASE&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;

    &lt;properties&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;java.version&gt;1.8&lt;/java.version&gt;
        &lt;log4j.version&gt;2.4.1&lt;/log4j.version&gt;
        &lt;commons.lang3.version&gt;3.3.2&lt;/commons.lang3.version&gt;
        &lt;guava.version&gt;19.0&lt;/guava.version&gt;
        &lt;swagger.version&gt;2.4.0&lt;/swagger.version&gt;
        &lt;surefire.junit47.version&gt;2.18.1&lt;/surefire.junit47.version&gt;
        &lt;rest-assured.version&gt;2.8.0&lt;/rest-assured.version&gt;
        &lt;jacoco.version&gt;0.7.5.201505241946&lt;/jacoco.version&gt;
        &lt;powermock.version&gt;1.6.4&lt;/powermock.version&gt;
        &lt;commons.io.version&gt;2.4&lt;/commons.io.version&gt;
        &lt;httpclient.version&gt;4.5.1&lt;/httpclient.version&gt;
        &lt;jayway.jsonpath.version&gt;2.2.0&lt;/jayway.jsonpath.version&gt;
        &lt;jjwt.version&gt;0.6.0&lt;/jjwt.version&gt;
        &lt;docker.image.prefix&gt;app&lt;/docker.image.prefix&gt;
        &lt;docker.spotify.plugin.version&gt;0.4.5&lt;/docker.spotify.plugin.version&gt;
        &lt;jacoco.maven.plugin.version&gt;0.7.7.201606060606&lt;/jacoco.maven.plugin.version&gt;
        &lt;fongo.version&gt;2.0.11&lt;/fongo.version&gt;
        &lt;cucumber.version&gt;1.2.5&lt;/cucumber.version&gt;
        &lt;gatling.highcharts.version&gt;2.2.3&lt;/gatling.highcharts.version&gt;
        &lt;gatling.plugin.version&gt;2.2.1&lt;/gatling.plugin.version&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-actuator-docs&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-eureka&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-feign&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-hystrix&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-hystrix-dashboard&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-ribbon&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-sleuth&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-sleuth-zipkin&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-mongodb&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security.oauth&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-oauth2&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-jwt&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.dropwizard.metrics&lt;/groupId&gt;
            &lt;artifactId&gt;metrics-core&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;
            &lt;version&gt;${swagger.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;
            &lt;version&gt;${swagger.version}&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;!-- Utility --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.logentries&lt;/groupId&gt;
            &lt;artifactId&gt;logentries-appender&lt;/artifactId&gt;
            &lt;version&gt;RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt;
            &lt;artifactId&gt;log4j-api&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;commons-io&lt;/groupId&gt;
            &lt;artifactId&gt;commons-io&lt;/artifactId&gt;
            &lt;version&gt;${commons.io.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
            &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt;
            &lt;version&gt;${commons.lang3.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;
            &lt;artifactId&gt;httpclient&lt;/artifactId&gt;
            &lt;version&gt;${httpclient.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.google.guava&lt;/groupId&gt;
            &lt;artifactId&gt;guava&lt;/artifactId&gt;
            &lt;version&gt;${guava.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.jayway.jsonpath&lt;/groupId&gt;
            &lt;artifactId&gt;json-path&lt;/artifactId&gt;
            &lt;version&gt;${jayway.jsonpath.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;
            &lt;artifactId&gt;jjwt&lt;/artifactId&gt;
            &lt;version&gt;${jjwt.version}&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;com.fasterxml.jackson.datatype&lt;/groupId&gt;
            &lt;artifactId&gt;jackson-datatype-jsr310&lt;/artifactId&gt;
            &lt;version&gt;2.6.5&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;!-- Test Dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.powermock&lt;/groupId&gt;
            &lt;artifactId&gt;powermock-module-junit4&lt;/artifactId&gt;
            &lt;version&gt;${powermock.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.powermock&lt;/groupId&gt;
            &lt;artifactId&gt;powermock-api-mockito&lt;/artifactId&gt;
            &lt;version&gt;${powermock.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.jayway.restassured&lt;/groupId&gt;
            &lt;artifactId&gt;rest-assured&lt;/artifactId&gt;
            &lt;version&gt;${rest-assured.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;/exclusions&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.jayway.restassured&lt;/groupId&gt;
            &lt;artifactId&gt;spring-mock-mvc&lt;/artifactId&gt;
            &lt;version&gt;${rest-assured.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;de.flapdoodle.embed&lt;/groupId&gt;
            &lt;artifactId&gt;de.flapdoodle.embed.mongo&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;info.cukes&lt;/groupId&gt;
            &lt;artifactId&gt;cucumber-java&lt;/artifactId&gt;
            &lt;version&gt;${cucumber.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;info.cukes&lt;/groupId&gt;
            &lt;artifactId&gt;cucumber-junit&lt;/artifactId&gt;
            &lt;version&gt;${cucumber.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;info.cukes&lt;/groupId&gt;
            &lt;artifactId&gt;cucumber-spring&lt;/artifactId&gt;
            &lt;version&gt;${cucumber.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;io.gatling.highcharts&lt;/groupId&gt;
            &lt;artifactId&gt;gatling-charts-highcharts&lt;/artifactId&gt;
            &lt;version&gt;${gatling.highcharts.version}&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.springframework.cloud&lt;/groupId&gt;
                &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
                &lt;version&gt;Camden.SR5&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;

    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
            &lt;/plugin&gt;
            &lt;!-- Package as a docker image --&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;com.spotify&lt;/groupId&gt;
                &lt;artifactId&gt;docker-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;${docker.spotify.plugin.version}&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;serverId&gt;docker-hub&lt;/serverId&gt;
                    &lt;imageName&gt;${docker.image.prefix}/${project.artifactId}&lt;/imageName&gt;
                    &lt;dockerDirectory&gt;src/main/docker&lt;/dockerDirectory&gt;
                    &lt;resources&gt;
                        &lt;resource&gt;
                            &lt;targetPath&gt;/&lt;/targetPath&gt;
                            &lt;directory&gt;${project.build.directory}&lt;/directory&gt;
                            &lt;include&gt;${project.build.finalName}.jar&lt;/include&gt;
                        &lt;/resource&gt;
                    &lt;/resources&gt;
                    &lt;imageTags&gt;
                        &lt;imageTag&gt;${project.version}&lt;/imageTag&gt;
                    &lt;/imageTags&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
            &lt;!-- Runs Code Coverage Reports --&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
                &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;${jacoco.maven.plugin.version}&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;pre-unit-test&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;post-unit-test&lt;/id&gt;
                        &lt;phase&gt;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;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;excludes&gt;
                        &lt;exclude&gt;**/*IntegrationTest.java&lt;/exclude&gt;
                    &lt;/excludes&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

    &lt;profiles&gt;
        &lt;profile&gt;
        &lt;id&gt;cucumber-tests&lt;/id&gt;
        &lt;build&gt;
            &lt;plugins&gt;
                &lt;plugin&gt;
                    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                    &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
                    &lt;configuration&gt;
                        &lt;excludes&gt;
                            &lt;exclude&gt;none&lt;/exclude&gt;
                        &lt;/excludes&gt;
                        &lt;includes&gt;
                            &lt;!-- Include your Cucumber tests, as an example --&gt;
                            &lt;exclude&gt;**/*IntegrationTest.java&lt;/exclude&gt;
                            &lt;exclude&gt;**/*Simulation.scala&lt;/exclude&gt;
                        &lt;/includes&gt;
                    &lt;/configuration&gt;
                &lt;/plugin&gt;
            &lt;/plugins&gt;
        &lt;/build&gt;
        &lt;/profile&gt;
        &lt;profile&gt;
            &lt;id&gt;gatling-tests&lt;/id&gt;
            &lt;build&gt;
                &lt;plugins&gt;
                    &lt;plugin&gt;
                        &lt;groupId&gt;io.gatling&lt;/groupId&gt;
                        &lt;artifactId&gt;gatling-maven-plugin&lt;/artifactId&gt;
                        &lt;version&gt;${gatling.plugin.version}&lt;/version&gt;
                        &lt;executions&gt;
                            &lt;execution&gt;
                                &lt;goals&gt;
                                    &lt;goal&gt;execute&lt;/goal&gt;
                                &lt;/goals&gt;
                                &lt;configuration&gt;
                                    &lt;simulationClass&gt;com.app.comment.gatling.MicroserviceServiceSimulation&lt;/simulationClass&gt;
                                &lt;/configuration&gt;
                            &lt;/execution&gt;
                        &lt;/executions&gt;
                        &lt;configuration&gt;
                            &lt;configFolder&gt;${project.basedir}/src/test/resources&lt;/configFolder&gt;
                            &lt;dataFolder&gt;${project.basedir}/src/test/resources/data&lt;/dataFolder&gt;
                            &lt;resultsFolder&gt;${project.basedir}/target/gatling/results&lt;/resultsFolder&gt;
                            &lt;bodiesFolder&gt;${project.basedir}/src/test/resources/bodies&lt;/bodiesFolder&gt;
                            &lt;simulationsFolder&gt;${project.basedir}/src/test/scala&lt;/simulationsFolder&gt;
                            &lt;runDescription&gt;This-is-the-run-description&lt;/runDescription&gt;
                            &lt;!--    &lt;noReports&gt;false&lt;/noReports&gt; --&gt;
                            &lt;!--   &lt;reportsOnly&gt;directoryName&lt;/reportsOnly&gt; --&gt;
                            &lt;!--   &lt;simulationClass&gt;foo.Bar&lt;/simulationClass&gt; --&gt;
                            &lt;!--   &lt;jvmArgs&gt; --&gt;
                            &lt;!--     &lt;jvmArg&gt;-DmyExtraParam=foo&lt;/jvmArg&gt; --&gt;
                            &lt;!--   &lt;/jvmArgs&gt; --&gt;
                            &lt;!--    &lt;fork&gt;true&lt;/fork&gt; --&gt;
                            &lt;!--    &lt;propagateSystemProperties&gt;true&lt;/propagateSystemProperties&gt; --&gt;
                            &lt;!--   &lt;failOnError&gt;true&lt;/failOnError&gt; --&gt;
                        &lt;/configuration&gt;
                    &lt;/plugin&gt;
                &lt;/plugins&gt;
            &lt;/build&gt;
        &lt;/profile&gt;
    &lt;/profiles&gt;

&lt;/project&gt;
</code></pre>

<p><a href=""http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mongo-test"" rel=""noreferrer"">http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mongo-test</a></p>
",https://stackoverflow.com/questions/42317261/datamongotest-is-creating-a-null-mongotemplate,"['spring', 'mongodb', 'spring-boot', 'spring-data-mongodb', 'spring-boot-test']",5459,TRUE,7,3
ASP.NET Core Integration Test for controller action,"<p>Microsoft documentation (<a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing</a>) explain how to implement an integration test using the TestServer class. It is easy in case we are using WEB API because we get the serialized model as response from the action.</p>

<p>But in case I want to test a Controller action returning an HTML View containing some data, how can I evaluate that the page content is what I expect (avoiding to scan the HTML page contents) ?</p>
",https://stackoverflow.com/questions/42387047/asp-net-core-integration-test-for-controller-action,"['asp.net-core', 'asp.net-core-mvc', 'integration-testing']",773,FALSE,0,2
How to Run WebTest Example?,"<p>I'm trying to understand how to use <a href=""https://docs.pylonsproject.org/projects/webtest/en/latest/"" rel=""nofollow noreferrer"">WebTest</a> to do integration testing and I'm stuck on the first example.</p>

<p>I've tried to follow the instructions.  First I created a module that contains the code I want to test:</p>

<pre><code># functions.py
def application(environ, start_response):
    """"""docstring for application""""""
    # I added body, otherwise you get an undefined variable error
    body = 'foobar'
    headers = [('Content-Type', 'text/html; charset=utf8'),
               ('Content-Length', str(len(body)))]
    start_response('200 OK', headers)
    return [body]
</code></pre>

<p>Then I created a test runner file:</p>

<pre><code># test.py
from webtest import TestApp
from functions import application

app = TestApp(application)
resp = app.get('/')
assert resp.status == '200 OK'
assert resp.status_int == 200
</code></pre>

<p>When I execute test.py, I get the following error:</p>

<p>AssertionError: Iterator  returned a non- object: 'foobar'.</p>

<p>What do I need to do to make this sample code from the WebTest documentation run?</p>
",https://stackoverflow.com/questions/45256603/how-to-run-webtest-example,"['python', 'python-3.x', 'webtest']",637,TRUE,0,1
"undefined method `provider&#39; for nil:NilClass, RSpec, OmniAuth","<p>I'm trying to test an authenticated controller with RSpec and OmniAuth. I've followed the <a href=""https://github.com/omniauth/omniauth/wiki/Integration-Testing"" rel=""nofollow noreferrer"">integration testing</a> guide on their wiki. When I run the test, I get the following error:</p>

<pre><code>Failure/Error:
       where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.first_name = auth.info.first_name
        user.last_name = auth.info.last_name
        user.email = auth.info.email
        user.picture = auth.info.image
        user.save!
       end

     NoMethodError:
       undefined method `provider' for nil:NilClass
</code></pre>

<p>All relevant code is provided in this <a href=""https://gist.github.com/Carpetfizz/5dad0f0f8d5abe79cbe39d6d226cd5e0"" rel=""nofollow noreferrer"">gist</a>. My hunch is that the mock auth hash isn't being set somehow but I have no way of verifying that. I configure OmniAuth in <code>config/environments/test.rb</code> as shown in the Gist, and I'm pretty sure that file is ran when the application boots.</p>
",https://stackoverflow.com/questions/41474315/undefined-method-provider-for-nilnilclass-rspec-omniauth,"['ruby-on-rails', 'ruby', 'rspec', 'omniauth', 'omniauth-google-oauth2']",1694,TRUE,0,1
How do I implement Typescript webdriverio for the SpectronClient?,"<p><a href=""https://github.com/electron/spectron"" rel=""nofollow noreferrer"">Spectron</a> is a <a href=""https://nodejs.org/"" rel=""nofollow noreferrer"">node.js</a> framework for automating <a href=""https://github.com/electron/electron"" rel=""nofollow noreferrer"">Electron</a> apps.  I'm using Spectron along with <a href=""https://github.com/avajs/ava"" rel=""nofollow noreferrer"">AVA</a> and <a href=""https://www.typescriptlang.org/"" rel=""nofollow noreferrer"">Typescript</a> to do automated Integration Testing.  I'm using <a href=""https://github.com/avajs/ava/blob/master/docs/recipes/typescript.md"" rel=""nofollow noreferrer"">AVA's suggest method</a> for making the test's context typesafe but I'm not able to figure out how to get typesafety on the Spectron's client property which is a <a href=""http://webdriver.io"" rel=""nofollow noreferrer"">webdriverio</a> client. I'm only able to see a few properties which the Spectron typescript definition file has provided and this is causing typescript transpile errors.</p>

<p>These are the errors I'm getting:</p>

<pre><code>src/pages/drive-shell.ts(7,34): error TS2339: Property 'waitForVisible' does not exist on type 'SpectronClient'.
src/pages/login.ts(7,34): error TS2339: Property 'waitForVisible' does not exist on type 'SpectronClient'.
src/pages/login.ts(11,21): error TS2339: Property 'setValue' does not exist on type 'SpectronClient'.
src/pages/login.ts(12,21): error TS2339: Property 'setValue' does not exist on type 'SpectronClient'.
src/pages/login.ts(13,21): error TS2339: Property 'click' does not exist on type 'SpectronClient'.
</code></pre>
",https://stackoverflow.com/questions/46816898/how-do-i-implement-typescript-webdriverio-for-the-spectronclient,"['typescript', 'webdriver-io', 'ava', 'spectron']",2677,TRUE,1,3
Spring RESTful webservice testing,"<p>I'm trying to figure out what type of testing i should do for my project layers.
I have made Controller->Service->DAO project model.
So I need to test DAO layer with unit tests and integration tests?
And Controller with unit tests and integration tests?
I just want to know how it has to be done in a professional way that code wont be overloaded :) And maybe some one has any links to of unit testing and integration testing for my case?</p>
",https://stackoverflow.com/questions/46858387/spring-restful-webservice-testing,"['spring', 'rest', 'unit-testing', 'integration-testing']",42,FALSE,0,1
SAVON passing XML as a request to wsdl and getting response as xml,"<p>I have a third party application and output of this application is an request xml which needs to be passed in to webservice (WSDL)</p>

<p>I need to do integration testing where i will be getting this request xml.</p>

<p>how can i pass this request xml using savon in Ruby ?
is there anyother way where we can pass request xml and get the output in response xml</p>

<p>i tried using soapui and it works but i am looking for native ruby solution</p>
",https://stackoverflow.com/questions/46430562/savon-passing-xml-as-a-request-to-wsdl-and-getting-response-as-xml,"['ruby', 'web-services', 'savon']",811,TRUE,0,1
pytest failure in a separate thread,"<p>We're adapting pytest for our integration testing, and trying to use pytest fixtures to spawn some background test environment monitoring using separate threads.</p>

<p>The monitor threads have no problem launching at startup when we use the fixture, but I haven't found a way for pytest to fail the main test if one of the background monitor threads detects a problem.</p>

<p>Does anyone know a nice way to accomplish this in pytest? Is there any hook that we could use in the main pytest thread to catch a pytest.fail being called in one of our background monitor threads?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/43791360/pytest-failure-in-a-separate-thread,"['python', 'multithreading', 'integration-testing', 'pytest']",2626,TRUE,11,2
Use Embedded MongoDB when active profile is &quot;test&quot;,"<p>I have</p>

<pre><code>&lt;dependency&gt;
  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
  &lt;artifactId&gt;spring-boot-starter-data-mongodb&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre>

<p>in my pom.xml so my Spring Boot application attempts to connect to MongoDB on localhost when the application is started.</p>

<p>I also have </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;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre>

<p>so when I run unit tests the embedded MongoDb is used.</p>

<p>For the purpose of integration testing, I'd like to also use the embedded MongoDB if the application is started with the ""test"" active profile.</p>

<p>So effectively, I'd like to remove <code>&lt;scope&gt;test&lt;/scope&gt;</code> from the embed dependency and have the the embed version used when the active profile is 'test'.</p>

<p>How can I achieve this?</p>
",https://stackoverflow.com/questions/45032261/use-embedded-mongodb-when-active-profile-is-test,"['spring', 'mongodb', 'spring-boot', 'integration-testing']",1295,TRUE,5,2
Why are files getting deleted from the bin folder when I run the tests?,"<p>I have a .NET framework 4.5 solution and I'm trying to setup integration testing for an existing project. This solution contains a unit test project (<strong>project A</strong>) that references to a project that provides the base for integration testing (<strong>project B</strong>). This project references an other project that has al db up scripts to create the current version of the database (<strong>project C</strong>).</p>

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

<p>The copy to output directory option of the sql scripts in the database project (<strong>project C</strong>) is set to 'copy always', so that these script will be copied to the bin directory of the executing project. </p>

<p>When I build the unit test project (<strong>project A</strong>) indeed all sql script of the database project (<strong>project C</strong>) are being copied to the bin folder of unit test project (<strong>project A</strong>) (and also to the bin of <strong>project B</strong>). So far so good..</p>

<p>But when I run or debug a test in the unit test project (<strong>project A</strong>) all files from the database project (<strong>project C</strong>) in the bin of the unit test project (<strong>project A</strong>) are deleted before the first break point get hit (Assembly initialize)</p>

<p>Is there any way that these files will stay in the bin folder of the unit test project? Can someone explain why this is happening? </p>
",https://stackoverflow.com/questions/46182569/why-are-files-getting-deleted-from-the-bin-folder-when-i-run-the-tests,"['c#', '.net', 'unit-testing', 'msbuild', 'integration-testing']",193,FALSE,0,0
How to trigger onChange with casperjs and React?,"<p>So, it appears that by calling <code>$('#input').val('email@example').change()</code>, it doesn't trigger the React input <code>onChange</code> event.</p>

<p>But this is really necessary for using something like <em>CasperJS</em> for integration testing (filling out a form and submitting, etc.). </p>

<p>So how to do this? I haven't been able to find a solution online or by trying various things in the browser and looking at the React Devtools value of the state.</p>

<p>Here are some related links, that aren't particularly helpful.
<a href=""https://stackoverflow.com/questions/3961469/why-jquery-val-value-does-not-dispatch-any-event-from-the-dom-element/3961475#3961475"">Why jQuery.val( value ) does not dispatch any event from the DOM element?</a></p>
",https://stackoverflow.com/questions/41993354/how-to-trigger-onchange-with-casperjs-and-react,"['javascript', 'reactjs', 'casperjs']",254,FALSE,1,1
Skipping Pundit authorization with Minitest,"<p>I have tests setup for Pundit no problem using:</p>

<p><a href=""https://github.com/ksimmons/policy-assertions"" rel=""nofollow noreferrer"">https://github.com/ksimmons/policy-assertions</a></p>

<p>In my case I have my Pundit / Devise system supplemented with an enrollment type system to add roles etc.</p>

<p>When I test my controllers I want to skip the entire Devise / Pundit system entirely and focus on just the controller logic and not look at authorization which I will handle in my policy tests.</p>

<p>I am looking something like this (<a href=""http://www.colorfultyping.com/disabling-devise-for-rails-integration-testing/#comment-4718"" rel=""nofollow noreferrer"">http://www.colorfultyping.com/disabling-devise-for-rails-integration-testing/#comment-4718</a>) but I can't get it to work.</p>
",https://stackoverflow.com/questions/42743827/skipping-pundit-authorization-with-minitest,"['ruby-on-rails', 'devise', 'minitest', 'pundit']",1095,TRUE,3,1
How do I remove AfterMap from Automapper Profiles,"<p>I have a profile class where I am using AfterMap() method. My profile class has two constructor dependencies. Problem is that while I am unit testing I am mocking these dependencies but also I require the actual objects when I am doing integration testing. Since im using xUnit2, everything runs in parallel, so I have no control. So that is why I want to remove all the code from aftermap. Can someone tell me the approach for this ?
I am using structuremap as my IOC container.</p>
",https://stackoverflow.com/questions/46639737/how-do-i-remove-aftermap-from-automapper-profiles,"['.net', 'automapper', 'structuremap3', 'xunit2']",89,FALSE,0,0
Why use OWIN TestServer?,"<p>This article shows how to host an entire web API stack in memory for testing using OWIN:</p>

<p><a href=""http://www.davidwhitney.co.uk/Blog/2015/01/07/testing-an-asp-net-webapi-app-in-memory/"" rel=""nofollow noreferrer"">http://www.davidwhitney.co.uk/Blog/2015/01/07/testing-an-asp-net-webapi-app-in-memory/</a></p>

<p>Whereas this article shows using the OWIN TestServer to unit test controllers:</p>

<p><a href=""https://blog.jcorioland.io/archives/2014/04/01/using-owin-to-test-your-web-api-controllers.html"" rel=""nofollow noreferrer"">https://blog.jcorioland.io/archives/2014/04/01/using-owin-to-test-your-web-api-controllers.html</a></p>

<p>The difference I see is between the use of <code>TestServer.Create</code> and <code>WebApp.Start&lt;Startup&gt;</code></p>

<p>What is the key difference and why would you choose one over the other?</p>

<p>Is it simply the difference between unit testing controller methods as web api calls versus end-to-end integration testing in memory?</p>
",https://stackoverflow.com/questions/46088291/why-use-owin-testserver,"['testing', 'asp.net-web-api', 'owin-middleware']",4099,TRUE,8,1
Spock + Gradle. Parallel tests execution,"<p>I'm using <strong>gradle + spock + groovy</strong> for integration testing. For now my test suite execution time is about 1h. So I've decided to look into parallel tests execution.</p>

<p>Gradle can parallel tests with the help of forks (<a href=""https://docs.gradle.org/current/dsl/org.gradle.api.tasks.testing.Test.html#org.gradle.api.tasks.testing.Test:maxParallelForks"" rel=""nofollow noreferrer"">maxParallelForks</a>). But in this case I'm limited with the (number of forks == number of cores on my machine).</p>

<p>Spock itself doesn't have support for parallel tests execution. </p>

<p>So my question: is there any gradle plugin (or test framework) similar to <a href=""http://maven.apache.org/surefire/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html"" rel=""nofollow noreferrer"">maven-surefire-plugin</a> that have both options for parallel test execution (via Threads and Forks)? </p>
",https://stackoverflow.com/questions/44673176/spock-gradle-parallel-tests-execution,"['gradle', 'fork', 'integration-testing', 'spock']",1766,TRUE,2,1
"HtmlUnit, how to check if every asset was loaded?","<p>I am using <a href=""http://htmlunit.sourceforge.net/"" rel=""nofollow noreferrer"" title=""HtmlUnit"">HtmlUnit</a> for integration-testing. </p>

<p>In HtmlUnit, there is <a href=""http://htmlunit.sourceforge.net/apidocs/com/gargoylesoftware/htmlunit/WebResponse.html#getStatusCode"" rel=""nofollow noreferrer"" title=""WebResponse::getStatusCode()"">WebResponse::getStatusCode()</a> for accessing <code>HTTP_STATUS_CODE</code> of currently loaded page. Let's say, my <a href=""http://htmlunit.sourceforge.net/apidocs/com/gargoylesoftware/htmlunit/Page.html"" rel=""nofollow noreferrer"" title=""Page"">Page</a> is ""about"" google.com, statusCode will be 200, usually.</p>

<p>I am wondering, if it is possible with HtmlUnit to check, if all required assets (*.css, *.js) were loaded successfully (200 &lt;= statusCode &lt; [300|400]).</p>

<p>In my use case, my tested page works fine - but a .css-file is missing, so the layout is broken. I would like to assert in my test-case, that each required assert can be loaded.</p>
",https://stackoverflow.com/questions/43086735/htmlunit-how-to-check-if-every-asset-was-loaded,"['java', 'htmlunit']",105,TRUE,1,1
"ASP.NET Core WebAPi, TestHost and [FromBody] parameters for Integration Test","<p>I've got an ASP.NET core WebAPI project that is already in use and i want to start integration tests for automation.</p>

<p>The controllers have nothing else than basic:</p>

<pre><code>[HttpPost]
public IActionResult Post([FromBody]string req)
{
    var dto = JsonConvert.DeserializeObject&lt;DTO&gt;(req);
    this.service.Create(dto);
    return Json(dto.Id);
}
</code></pre>

<p>I'm using Microsoft.AspNetCore.TestHost for creating the client and server to run the integration testing, bu then when i want to send the payload over the client the controller on the WebApi does not found the parameter mark as [FromBody]. I have already tested on postman sending an string on the body of the post method and is working right, so, what I'm doing wrong?</p>

<pre><code>[Fact]
public async Task Execute()
{
    // Act
    var dto = new DTO() { Field1 = ""Filed1"" ...};

    var json = JsonConvert.SerializeObject(dto);

    HttpContent payload = new StringContent(json, Encoding.UTF8, ""application/json"");

    var response = await client.PostAsync(""/api/sample"", payload);

    response.EnsureSuccessStatusCode();
}
</code></pre>
",https://stackoverflow.com/questions/47082018/asp-net-core-webapi-testhost-and-frombody-parameters-for-integration-test,"['c#', 'asp.net-web-api', 'integration-testing', 'asp.net-core-testhost']",1774,FALSE,1,0
Can I create sequential integration test in Nunit 3 passing parameter between them,"<p>So I want to run first test that creates a object in DB, then I want to pass the id to the next tests in succession that test get,alter,delete. This should ensure the object is deleted at the end.</p>

<p>I know this isn't the preferred method of integration testing against DB, but there are external resources we can't control and this has been requested.</p>

<p>I can't use <code>TestCaseSource</code> as later tests wouldn't know if I added anything to it because they are all created before being run.</p>
",https://stackoverflow.com/questions/42651606/can-i-create-sequential-integration-test-in-nunit-3-passing-parameter-between-th,"['nunit', 'integration-testing', 'nunit-3.0']",83,TRUE,1,1
Mocha with chai and supertest: expected undefined to equal,"<p>I wrote the unit tests:  </p>

<pre><code>var app = require('../server');
var chai = require('chai');
var supertest = require(""supertest"")(app);
var GoogleUrl = require('google-url');
var config = require('../config');

var expect = chai.expect;

describe('Urls Tests', function () {

  var url = {
    author : 'Alexey',
    description : 'grrggr',
    full_url : 'https://github.com',
    date : '30-06-2017',
    time : '18:21:27',
    count_click : 0,
    list_tags : [
      'Sport',
      'Football'
    ]
  };

  var token;

  beforeEach(function (done) {
    agent
      .post('http://localhost:8000/auth/login')
      .send({email: 'Keane95@yandex.ru', password: '123456'})
      .end(function (err, res) {
        if (err) {
          return done(err);
        }

        expect(res.body.userData).to.have.property('token');
        token = res.body.userData.token;
        done();
      });
  });

  it('should create a url', function(done) {

      var googleUrl = new GoogleUrl({
        'key': config.get('google_key')
      });

      googleUrl.shorten(url.full_url, function (err, shortUrl) {

        url.short_url = shortUrl;

        supertest
          .post('/urls/create')
          .send(url)
          .expect(401)
          .end(function (err, res) {
            if (err) return done(err);
            expect(res.body.author).to.equal('Alexey');
            url = res.body;
            done();
          });
      });

    });

  it('should modify a url by id', function(done) {
      url.description = 'Good description';
      url.list_tags.push('Liverpool');
      supertest
        .put('/urls/' + url._id)
        .send(url)
        .expect(401)
        .end(function(err, res) {
          if (err) return done(err);
          expect(res.body.description).to.equal('Good description');
          expect(res.body.list_tags[2]).to.equal('Liverpool');
          done();
        });
    });

  it('should modify a count of clicks', function(done) {
      url.count_click++;
      supertest
        .put('/urls/' + url._id)
        .send(url)
        .expect(401)
        .end(function(err, res) {
          if (err) return done(err);
          expect(res.body).to.equal('Count of the click is updated');
          done();
        });
    });

});
</code></pre>

<p>I run to execute the unit tests and get the errors:<br>
<a href=""https://i.stack.imgur.com/ARL2E.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ARL2E.png"" alt=""enter image description here""></a></p>

<p>I read the articles by unit tests.<br>
First article: <a href=""http://developmentnow.com/2015/02/05/make-your-node-js-api-bulletproof-how-to-test-with-mocha-chai-and-supertest/"" rel=""nofollow noreferrer"">http://developmentnow.com/2015/02/05/make-your-node-js-api-bulletproof-how-to-test-with-mocha-chai-and-supertest/</a><br>
Second article: <a href=""https://www.codementor.io/olatundegaruba/integration-testing-supertest-mocha-chai-6zbh6sefz"" rel=""nofollow noreferrer"">https://www.codementor.io/olatundegaruba/integration-testing-supertest-mocha-chai-6zbh6sefz</a>  </p>

<p>I don't understand why I get these errors. Please, help me. I think that I made little error, but since I cannot fint it.</p>

<p><strong><em>UPDATED</em></strong><br>
I added route:  </p>

<pre><code>var express = require('express');
var GoogleUrl = require('google-url');
var _ = require('lodash');
var token = require('../middlewares/token');
var Url = require('../models/url');
var config = require('../config');
var router = express();

router.post('/create', token.required, createShortUrl);
router.put('/count/:id', token.required, updateCountClick);
router.put('/:id', token.required, updateUrlById);

module.exports = router;

function createShortUrl(req, res) {

    _.trim(req.body.list_tags);
    var tags = _.split(req.body.list_tags, ',');
    tags.splice(tags.length - 1, 1);

    var date = returnDate();
    var time = returnTime();

    var googleUrl = new GoogleUrl({
        'key': config.get('google_key')
    });

    googleUrl.shorten(req.body.full_url, function (err, shortUrl) {

        if (err) {
            res.status(500).json(err);
        }

        var url = new Url({
            'author': req.payload.username,
            'description': req.body.description,
            'full_url': req.body.full_url,
            'short_url': shortUrl,
            'list_tags': tags,
            'date': date,
            'time': time
        });

        url.save(function (err, url) {

            if (err) {
                return res.status(500).json(err);
            } else {
                return res.status(200).json(url);
            }

        });

    });

}

function updateCountClick(req, res) {

    var count_click = req.body.count_click + 1;

    Url.findOneAndUpdate({_id: req.params.id}, {$set: {count_click: count_click}}, {new: true}, function (err, url) {

        if (err) {
            return res.status(500).json(err);
        }

        if (url) {
            return res.status(200).json('Count of the click is updated');
        }

    });
}

function updateUrlById(req, res) {

    _.trim(req.body.list_tags);
    var tags = _.split(req.body.list_tags, ',');
    tags.splice(tags.length - 1, 1);

    Url.findOneAndUpdate({_id: req.params.id}, {$set: {description: req.body.description, list_tags: tags}}, {new: true}, function (err, url) {

        if (err) {
            res.status(500).json(err);
        }

        if (url) {
            res.status(200).json(url);
        }

    });

}
</code></pre>

<p><strong><em>UPDATED 2</em></strong></p>

<p>Authoziration was added: </p>

<pre><code>var token;

beforeEach(function (done) {
    agent
      .post('http://localhost:8000/auth/login')
      .send({email: 'Keane95@yandex.ru', password: '123456'})
      .end(function (err, res) {
        if (err) {
          return done(err);
        }

        expect(res.body.userData).to.have.property('token');
        token = res.body.userData.token;
        done();
      });
  }); 
</code></pre>

<p>Also I updated code my unit-tests.</p>
",https://stackoverflow.com/questions/44883026/mocha-with-chai-and-supertest-expected-undefined-to-equal,"['node.js', 'unit-testing', 'mocha.js', 'chai', 'supertest']",1116,TRUE,0,1
Spring/DBUnit dont rollback transaction until the end of test,"<p>We are using dbunit with spring boot and H2 database for local unit/integration testing. In the test we are using <code>TransactionDbUnitTestExecutionListener</code> and <code>@Transactional</code> annotations so that the transaction during the test does not rollback until the end. </p>

<p>However, I observed that if in the test I call a function with <code>Propogation.REQUIRES_NEW</code>, the rollback occurs immediately after the function returns and then test fails because it cannot find the data. </p>

<p>Here is the example code</p>

<pre><code>@Test
@Transactional
@DatabaseSetup(""/Uploads.xml"")
@Rollback(value = false)
fun testStampSidekiqJobId() {
    uploadEntity = uploadService.stampSidekiqJobId(uploadEntity, ""fakeJobId"")
    // test values
}

// here is the called function
@Transactional(propagation = Propagation.REQUIRES_NEW)
open fun stampSidekiqJobId(uploadEntity:UploadEntity, encodeJobId:String): UploadEntity {
</code></pre>

<p>I have tried with and without Rollback annotation. Please note that the class hosting this unit test has <code>DependencyInjectionTestExecutionListener</code>, <code>TransactionDbUnitTestExecutionListener</code> annotations. </p>
",https://stackoverflow.com/questions/43663662/spring-dbunit-dont-rollback-transaction-until-the-end-of-test,"['java', 'unit-testing', 'spring-boot', 'transactions', 'dbunit']",747,FALSE,0,0
"How do I get polymorphic tests working with cucumber-jvm, cucumber-serenity and SerenityObjectFactory","<p>I found an interesting blog explaining in general how to realize polymorphic step definitions using cucumber bdd and picocontainer dependency injection. You can visit the blog <a href=""https://cucumber.io/blog/2015/07/08/polymorphic-step-definitions"" rel=""nofollow noreferrer"">here</a> </p>

<p>Where I get stuck is not knowing how to keep the automation logic behind a ""generic"" interface and then provide two different implementations, One that talks directly to the domain model for unit-integration testing, and another one that uses Selenium WebDriver for UI-testing. </p>

<p>Can someone give me advise/skeleton how to implement this. I can't thank you enough for helping the community.</p>
",https://stackoverflow.com/questions/44522612/how-do-i-get-polymorphic-tests-working-with-cucumber-jvm-cucumber-serenity-and,"['java', 'dependency-injection', 'cucumber', 'cucumber-jvm', 'cucumber-serenity']",388,TRUE,0,1
In-memory integration tests and Environment Variables -- .net core,"<p>We can execute a test server for integration testing. Something like:</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/29968788/how-do-i-run-in-memory-integration-tests-using-xunit-net-and-asp-net-5"">this question</a> or the <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""noreferrer"">MS docs</a></li>
</ul>

<p>Fine.</p>

<p>However, I can't pass environment variables to the test server.
I can set the environment with <code>UseEnvironment(""Development"")</code> but not add variables.
It should be possible, but I don't know how to do it.</p>

<p>Anyone Knows how this can be done?</p>

<hr>

<p>The environment variables would carry dev logins for a 3rd party API our code base needs.
For unit tests we mock this 3rd party API.
A solution for my specific problem can be to mock this for integration tests as well, thus removing the need for environment variables, but even so the question remains.</p>
",https://stackoverflow.com/questions/42030238/in-memory-integration-tests-and-environment-variables-net-core,"['c#', 'asp.net-core', 'environment-variables', 'integration-testing']",9328,TRUE,10,1
Pass data to startup.cs,"<p>How do you pass data into startup.cs ?</p>

<p>This is for integration testing using <code>WebHostBuilder</code> and <code>TestServer</code></p>

<p>I need to pass different data depending on the Test Fixture. So dont want to pull it in from a config file, for example</p>

<p>The data will be supplied to a registered Middleware in startup.cs</p>

<p>Docs seem to suggest this should work:</p>

<pre><code>var configBuilder = new ConfigurationBuilder()
                .AddInMemoryCollection(new[]
                {
                    new KeyValuePair&lt;string, string&gt;(""key"", ""value""),
                });

            var configuration = configBuilder.Build();

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseConfiguration(configuration) // config added here
                .UseStartup&lt;Startup&gt;()
                .Build();

            host.Run();
</code></pre>

<p>but when I inspect the Configuration object in startup.cs, the key is not present. And only the providers defined in startup.cs are available.</p>

<p>I am trying to do this in program.cs at the moment to test the concept, then will move to integration tests later</p>

<p>any ideas what I'm doing wrong?</p>

<p>Is there a better way to pass data into startup?</p>
",https://stackoverflow.com/questions/44721426/pass-data-to-startup-cs,"['c#', '.net-core']",8171,TRUE,15,3
"Git workflow design goals met, but it ain&#39;t pretty in practice","<p>Firstly: We understand why Git does what it's doing. We're looking for a practical way to <em>deal with it</em>. Please do not assume we know nothing about Git. We may not know everything but we've spent many hours researching a solution to the problem below. </p>

<p>Several months ago I and another developer on my team started designing a Git workflow for the rest of our team. Our company currently uses TFSVC. </p>

<p><strong>Our design goals included the following:</strong></p>

<ol><li>Allow isolated testing of features  </li>
<li>Allow integration testing of features  </li>
<li>Prevent developers from taking dependencies on unreleased code (this is very important)</li>
</ol>

<p><strong>The workflow we've landed on is this:</strong></p>

<ol>
<li>developer pulls origin/master</li>
<li>developer branches master (topic)</li>
<li>development happens</li>
<li>topic branch published to origin </li>
<li>testing happens on origin/topic (in isolation)</li>
<li>pull request results in origin/topic branch(es) being merged to origin/develop branch</li>
<li>testing happens (integration testing)</li>
<li>pull request results in origin/develop being merged to origin/release branch</li>
<li>more testing happens (seems redundant but it's really not...details left out for brevity)</li>
<li>origin/release merged to origin/master, code deployed to production</li>
</ol>

<p>The practical upshot of the above steps is that we hit our design goals: isolated testing, integration testing and the piece de resistance is that no developer can take any dependencies on code that hasn't gone through testing and isn't already in production.</p>

<p>All great stuff. But....our commits always snowball. That is to say that once a topic branch’s changes make it all the way through to origin/master and devs pull from origin/master to start the process all over again, we find that pull requests to develop (step 6 above) contain all previous commits. We understand that they only look the same as the previous commits--they're actually different commits, it's the fact that those commits are merged to several branches in succession (and hence have different hashes) that they ""come back"" over and over.</p>

<p>My question is: can we prune out the ""duplicates""? Or can we tell Git to somehow ignore the ""duplicates""? </p>

<p>If not, is there any other practical way to deal with this phenomena? Perhaps an adjustment to our workflow that doesn’t add much complexity and still hits all the design goals?</p>
",https://stackoverflow.com/questions/43530250/git-workflow-design-goals-met-but-it-aint-pretty-in-practice,"['git', 'tfs', 'workflow']",158,TRUE,0,2
aem-mocks property test a servlet,"<p>Trying to write some proper AEM integration tests using the aem-mocks framework. The goal is to try and test a servlet by calling its path,</p>

<p>E.g. an AEM servlet</p>

<pre><code>@SlingServlet(
        paths = {""/bin/utils/emailSignUp""},
        methods = {""POST""},
        selectors = {""form""}
)
public class EmailSignUpFormServlet extends SlingAllMethodsServlet {

    @Reference
    SubmissionAgent submissionAgent;

    @Reference
    XSSFilter xssFilter;

    public EmailSignUpFormServlet(){

    }

    public EmailSignUpFormServlet(SubmissionAgent submissionAgent, XSSFilter xssFilter) {
        this.submissionAgent = submissionAgent;
        this.xssFilter = xssFilter;
    }

    @Override
    public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {

        String email = request.getParameter(""email"");
        submissionAgent.saveForm(xssFilter.filter(email));

    }
}
</code></pre>

<p>Here is the corresponding test to try and do the integration testing. Notice how I've called the servlet's 'doPost' method, instead of 'POST'ing via some API. </p>

<pre><code>public class EmailSignUpFormServletTest {

    @Rule
    public final AemContext context = new AemContext();

    @Mock
    SubmissionAgent submissionAgent;

    @Mock
    XSSFilter xssFilter;

    private EmailSignUpFormServlet emailSignUpFormServlet;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);
        Map&lt;String,String&gt; report = new HashMap&lt;&gt;();
        report.put(""statusCode"",""302"");
        when(submissionAgent.saveForm(any(String.class)).thenReturn(report);
    }

    @Test
    public void emailSignUpFormDoesNotRequireRecaptchaChallenge() throws IOException {


        // Setup test email value
        context.request().setQueryString(""email=test.only@mail.com"");

        //===================================================================
        /*
         * WHAT I END UP DOING:
         */
        // instantiate a new class of the servlet 
        emailSignUpFormServlet = new EmailSignUpFormServlet(submissionAgent, xssFilter);

        // call the post method (Simulate the POST call)
        emailSignUpFormServlet.doPost(context.request(),context.response());

        /*
         * WHAT I WOULD LIKE TO DO:          
         */
        // send request using some API that allows me to do post to the framework
        // Example:
        // context.request().POST(""/bin/utils/emailSignUp"")  &lt;--- doesn't exist!
        //===================================================================

        // assert response is internally redirected, hence expected status is a 302
        assertEquals(302,context.response().getStatus());
    }

}
</code></pre>

<p>I've done a lot of research on how this could be done (<a href=""https://sling.apache.org/documentation/development/sling-mock.html"" rel=""nofollow noreferrer"">here</a>) and (<a href=""http://wcm.io/testing/aem-mock/usage.html"" rel=""nofollow noreferrer"">here</a>), and these links show a lot about how you can set various parameters for context.request() object. However, they just don't show how to finally execute the 'post' call.</p>
",https://stackoverflow.com/questions/41833922/aem-mocks-property-test-a-servlet,"['unit-testing', 'osgi', 'aem']",1512,TRUE,1,1
React 16 upgrade results in eslint error explosion,"<p>has anyone seen upgrade to react 16 break all eslint rules?</p>

<p>i've encountered this twice. once when I performed a broad swath of updates to npm packages. Then again when I took a very granular approach*.</p>

<p>here is the upgrade that resulted in copious eslint messages:</p>

<pre><code>-""react"": ""15.6.2"",
+""react"": ""16.0.0"",
-""react-dom"": ""15.6.2"",
+""react-dom"": ""16.0.0"",
""react-hot-loader"": ""^3.0.0-beta.6"",
""react-redux"": ""^4.4.5"",
-""react-router"": ""3.2.0"",
+""react-router"": ""4.2.0"",
</code></pre>

<p>lint messages occur when running webpack-dev-server, and include these examples.</p>

<pre><code>Use object destructuring  prefer-destructuring
Closing tag of a multiline JSX expression must be on its own line
Expected indentation of 2 spaces but found 27
defaultProp ""currentInput"" defined for isRequired propType
Block must not be padded by blank lines
</code></pre>

<p>*performed jest testing, lint, and integration testing and checked in one family of upgrades at a time.</p>

<p>when this happened before, I went and attempted to fix the reported eslint issues, but did not get React 16 to run.</p>
",https://stackoverflow.com/questions/47040242/react-16-upgrade-results-in-eslint-error-explosion,"['reactjs', 'eslint']",221,FALSE,1,0
Test nodejs server code without running server,"<p>New to nodejs testing.</p>

<p>I have a nodejs server that runs some complex server side logic, and I'm looking at building a unit test runner for that code. I do <strong><em>not</em></strong> want to run the server and tests sending it requests though, as that doesn't expose all the modules and functions I want to test on the server side. That will be more like integration testing. I just want to import those server side files, which are written as AMD modules, and call their functions one by one in unit tests.</p>

<p>What's the best way to go about doing this?</p>
",https://stackoverflow.com/questions/43774018/test-nodejs-server-code-without-running-server,"['node.js', 'unit-testing']",1365,TRUE,1,1
End-To-End Google API Tests,"<p>We have an application that uses a couple different Google APIs (Login, Classroom).  We originally wrote end-to-end tests to make sure that these integrations worked on a very basic level.  Unfortunately, it looks like our end-to-end tests have started failing because Google is detecting ""suspicious"" login activity from the Google accounts we created to do the integration testing and is presenting Captcha's etc..</p>

<p>Is there anyway to get Google to whitelist an account so that they don't run it through all their security checks?  We literally only use these accounts for automated testing.</p>
",https://stackoverflow.com/questions/44120334/end-to-end-google-api-tests,"['google-api', 'google-classroom']",208,FALSE,1,1
Is ChefSpec in chef really usable compared to testing with Kitchen,"<p>I had covered recipe code with ChefSpec and after that I have integration testing with Kitchen. To me at the end ChefSpec is not really usable just one extra think to maintain because:  </p>

<ul>
<li><p>When I'm writing Java with TDD/BDD I see real benefits from using this approach- lots of smaller classes, DI integration, modularity, less bugs.</p></li>
<li><p>However with Chef and ChefSpec to me is only usable default generated spec the helps me with some compile and syntax errors.</p></li>
</ul>

<p>How to use ChefSpec with Chef to see the same benefits like TDD/BDD in Java for example.</p>
",https://stackoverflow.com/questions/43162842/is-chefspec-in-chef-really-usable-compared-to-testing-with-kitchen,"['ruby', 'rspec', 'chef-infra']",1024,TRUE,1,2
Testing SOAP web services,"<p>I'd like to test a SOAP service. I'm using nUnit to test it, nevertheless I've no idea about how to mock them (using NSubstitute for example...).</p>

<p>Is there some stuff helping code over there?</p>

<p>How could I create integration tests?</p>

<p>I'm using C# .net projects...</p>

<p><strong>EDIT</strong></p>

<p>I''ve create a service which exposes an interface:</p>

<pre><code>&lt;services&gt;
  &lt;service name=""Core.Kernel""&gt;
    &lt;endpoint address="""" binding=""basicHttpBinding"" contract=""Core.Communication.ICoreService""&gt;
      &lt;identity&gt;
        &lt;dns value=""localhost"" /&gt;
      &lt;/identity&gt;
    &lt;/endpoint&gt;
    &lt;endpoint address=""mex"" binding=""mexHttpBinding"" contract=""IMetadataExchange"" /&gt;
    &lt;host&gt;
      &lt;baseAddresses&gt;
        &lt;add baseAddress=""http://localhost:8733/Core/"" /&gt;
      &lt;/baseAddresses&gt;
    &lt;/host&gt;
  &lt;/service&gt;
</code></pre>

<p>where, <code>Core.Communication.ICoreService</code> is:</p>

<pre><code>[ServiceContract]
public interface ICoreService
{
    [OperationContract]
    IEnumerable&lt;Core.Communication.Entities.Plugin&gt; GetPlugins(Communication.Entities.UserIdentity userIdentity);
    [OperationContract]
    IEnumerable&lt;Communication.Entities.ChannelPlugin&gt; GetPluginChannels(Communication.Entities.UserIdentity userIdentity);
    [OperationContract]
    IEnumerable&lt;Communication.Entities.ChannelPlugin&gt; GetPluginChannelsById(Communication.Entities.UserIdentity userIdentity, string pluginId);

    #region ICoreConfiguration interface

    [OperationContract]
    void AddUserIdentity(Communication.Entities.UserIdentity userIdentity);

    [OperationContract]
    void RemoveUserIdentity(Communication.Entities.UserIdentity userIdentity);

    #endregion

}
</code></pre>

<p>I've create an project which uses this service and I've set this as a service reference.</p>

<pre><code>public partial class UIController : UIFrame.Core.Controllable
{

    public IEnumerable&lt;UIContainer.Entities.Core.Plugin&gt; getPlugins()
    {
        this.service.GetPlugins()...;
    }

    public IEnumerable&lt;UIContainer.Entities.Core.ChannelPlugin&gt; getPluginChannels()
    {
        this.service.getPluginChannels()...;
    }

    public IEnumerable&lt;UIContainer.Entities.Core.ChannelPlugin&gt; getPluginChannelsById(string pluginId)
    {
        this.service.GetPluginChannelsById(...);
    }

    public void AddUserIdentity()
    {
        this.service.AddUserIdentity(this.coreUserIdentity);
    }

    public void RemoveUserIdentity()
    {
        this.service.RemoveUserIdentity(this.coreUserIdentity);
    }

}
</code></pre>

<p>As you can see I'm creating a slight wrapper of straightforward proxy of <code>service</code>.</p>

<p>I'd like to add integration testing in order to check connectivity, interface compatibility, and so on...</p>
",https://stackoverflow.com/questions/42203015/testing-soap-web-services,"['.net', 'unit-testing']",254,FALSE,0,0
Handling transitive dependencies in Arquillian,"<p>I am looking for a testing framework for integration testing of my application.</p>

<pre><code>class A {
    @Autowired
    B b;

    @Autowired
    C c;
}

class B {
    @Autowired
    D d;
}
</code></pre>

<p>I have a class A which has some service-level dependencies injected in it like B and C (e.g. Postgres and an internal microservice client). I understand that we can have self-contained external dependencies (Postgres, ElasticSearch) included in the Shrinkwrap part while creating test archive but what about transitive (nested) dependencies like B, where the service shrinkwrapped into an arquillian archive depends on yet another service that I would also normally shrinkwrap with arquillian. What's the best way to handle this sort of situation?</p>
",https://stackoverflow.com/questions/42403162/handling-transitive-dependencies-in-arquillian,"['integration-testing', 'jboss-arquillian']",105,FALSE,0,1
"Square Point of Sale API - Error code &quot;amount_too_small&quot;, but card is charged?","<p>i'm making calls to the square pos ios web api with charges of $1.00 for system integration testing.</p>

<p>the calls are successful, in that they switch control to the square app, the card gets charged $1.00, transactions show up in the dashboard, i can refund them, etc. so obviously i'm sending the minimum amount suggested in the documentation to test the api (<a href=""https://docs.connect.squareup.com/articles/web-api-ios"" rel=""nofollow noreferrer"">https://docs.connect.squareup.com/articles/web-api-ios</a>) due to the lack of a point of sale api sandbox?</p>

<p>why does the response return a status of ""error"" with an error_code of ""amount_too_small"" when it was processed successfully?</p>
",https://stackoverflow.com/questions/47357177/square-point-of-sale-api-error-code-amount-too-small-but-card-is-charged,['square-connect'],277,FALSE,0,1
"Promises not running with Mocha, in nodejs","<p>I have some code which makes use of promises, but it fails to run when run through Mocha. I have simplified it to the essentials:</p>

<pre><code>process.env.NODE_ENV = 'test';

const Promise = require('bluebird');

console.log('zzzz IN');
Promise.resolve('xxx').then(function(val) {
    console.log('[normal]', val);
}).catch(function(error) {
    console.log('[error]', error);

})
console.log('zzzz OUT');
</code></pre>

<p>when run via <code>node test/index.js</code> I get:</p>

<pre><code>zzzz IN
zzzz OUT
[normal] xxx
</code></pre>

<p>but via mocha:</p>

<pre><code>&gt; my-server@0.0.1 test /Users/ajmas/Development/mocha-and-promise
&gt; eslint lib &amp;&amp; mocha --timeout 10000

zzzz IN
zzzz OUT


0 passing (0ms)
</code></pre>

<p>Is this an issue in Mocha or in the way I have configured things?</p>

<p>Package.json:</p>

<pre><code>{
    ""name"": ""my-server"",
    ""version"": ""0.0.1"",
    ""description"": ""Mocha and Promises test case"",
    ""main"": ""lib/main.js"",
    ""scripts"": {
        ""start-dev"": ""NODE_ENV=dev node test/index.js"",
        ""start-dev-debug"": ""DEBUG=express:* npm run start-dev"",
        ""start"": ""node lib/main.js"",
        ""test"": ""eslint lib &amp;&amp; mocha --timeout 10000""
    },
    ""engines"": {
        ""node"": ""&gt;=6.7.0""
    },
    ""dependencies"": {
        ""bluebird"": ""^3.4.6""
    },
    ""devDependencies"": {
        ""chai"": ""^3.5.0"",
        ""chai-http"": ""^3.0.0"",
        ""eslint"": ""^3.8.1"",
        ""eslint-config-standard"": ""^6.2.1"",
        ""eslint-plugin-promise"": ""^3.3.0"",
        ""eslint-plugin-standard"": ""^2.0.1"",
        ""mocha"": ""^3.2.0""
    }
}
</code></pre>

<p>Running with node 6.7.0 on MacOS X 10.12.2. Have also tried with '<a href=""https://www.npmjs.com/package/bluebird"" rel=""nofollow noreferrer"">bluebird</a>', '<a href=""https://www.npmjs.com/package/promise"" rel=""nofollow noreferrer"">promise</a>' and native Promise, but same behaviour with each.</p>

<p>BTW this code is meant to be part of the application I am integration testing, but because no promises  are completing I can't launch the server from within Mocha.</p>
",https://stackoverflow.com/questions/41945587/promises-not-running-with-mocha-in-nodejs,"['node.js', 'promise', 'mocha.js', 'bluebird']",454,FALSE,0,1
How to properly configure mock dependencies for testing Web Api (ASP.NET Core) controllers using Autofac,"<p>I'm using ASP.NET Core (2.0) with <code>Autofac</code>, and a  <code>Microsoft.AspNetCore.TestHost.TestServer</code> for integration testing. However, for some test scenarios, I would like to inject some service mocks instead of the implementations loaded in <code>ConfigureContainer</code> method (as described here: <a href=""http://docs.autofac.org/en/latest/integration/aspnetcore.html#quick-start-with-configurecontainer"" rel=""nofollow noreferrer"">http://docs.autofac.org/en/latest/integration/aspnetcore.html#quick-start-with-configurecontainer</a>).</p>

<p>Example:</p>

<pre><code>public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .ConfigureServices(s =&gt; s.AddAutofac())
            .UseStartup&lt;Startup&gt;()
            .Build();

        host.Run();
    }
}

public class Startup
{
    ...
    public void ConfigureContainer(ContainerBuilder builder)
    {
        builder.RegisterModule(new Modules.ApiModule());
    }
    ...
}
</code></pre>

<p>And the test class:</p>

<pre><code>public class BasicControllerTests
{
    TestServer server;
    HttpClient client;

    public BasicControllerTests()
    {
        var resellerRepo = new Mock&lt;IResellerProvider&gt;();
        resellerRepo.Setup(a =&gt; a.Query())
            .Returns(new[] {
            new Model.Reseller
            {
                Id = Guid.NewGuid(),
                Code = ""R1"",
                Name = ""Reseller 1""
            }
            }.AsQueryable());

        // How to inject mock properly in the lines below?

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

        client = server.CreateClient();
    }
   ...
</code></pre>

<p>What I would like to do is to use the <code>TestServer</code> with all the dependencies as they are, but just the <code>IResellerProvider</code> mocked as in the test example. What is the best way to accomplish that? Of course, I could create a <code>TestStartup</code> class for this exact case, but I would like to know what is the proper way to handle this situation.</p>
",https://stackoverflow.com/questions/45858621/how-to-properly-configure-mock-dependencies-for-testing-web-api-asp-net-core-c,"['testing', 'asp.net-core', 'autofac', 'xunit']",1592,TRUE,4,1
Improve the performance of dacpac deployment using c#,"<p>We are deploying to <code>MS SQL Server</code> <code>localdb</code> for integration testing.</p>

<p>We build a Database Project and the resulting <code>dacpac</code> file is copied in order to be used by the IntegrationTests project. So far we have:</p>

<pre><code>DatabaseProject.sqlproj
    bin/debug/DatabaseProject.dacpac
IntegrationTests.csproj 
    bin/debug/DatabaseProject.dacpac
</code></pre>

<p>We have an assembly setup in the IntegrationTests project where a new fresh database is created and the <code>dacpac</code> is deployed to <code>localdb</code>. In the TearDown the database is deleted so we have a deterministic state for testing.</p>

<p>This is the code that deploys the <code>dacpac</code>, which uses <code>DacServices</code> (<code>Microsoft.SqlServer.Dac</code>, <code>System.Data.SqlLocalDb</code>, <code>System.Data.SqlClient</code>):</p>

<pre><code>public void CreateAndInitializeFromDacpac(
ISqlLocalDbInstance localDbInstance,
string databaseName,
string connectionString,
string dacpacPath)
{

    using (var cx = localDbInstance.CreateConnection())
    {
        cx.Open();
        using (var command = new SqlCommand(
            string.Format(""CREATE DATABASE {0}"", databaseName), cx))
            command.ExecuteNonQuery();
    }

    var svc = new DacServices(connectionString);

    svc.Deploy(
        DacPackage.Load(dacpacPath),
        databaseName,
        true
        );
}
</code></pre>

<p>We are having now a couple of database projects, and it takes about <strong>8s</strong> to deploy each one. That increases the overall time to execute the tests.</p>

<p>Is it possible somehow to improve the deploy performance of the <code>dacpac</code>?</p>
",https://stackoverflow.com/questions/43365451/improve-the-performance-of-dacpac-deployment-using-c,"['c#', 'sql-server', 'sql-server-data-tools', 'localdb', 'dacpac']",3938,TRUE,8,1
Using docker-compose vs codeship-services in my CI pipeline,"<p>I am building an app that has a couple of <code>microservices</code> and trying to prototype a <code>CI/CD</code> pipeline using <code>Codeship</code> and <code>Docker</code>.</p>

<p>I am a bit confused with the difference between using <code>codeship-services.yml</code> and <code>docker-compose.yml</code>. Codeship docs say - </p>

<blockquote>
  <p>By default, we look for the filename codeship-services.yml. In its
  absence, Codeship will automatically search for a docker-compose.yml
  file to use in its place.</p>
</blockquote>

<p>Per my understanding, <code>docker-compose</code> could be more appropriate in my case as I'd like to spin up containers for all the <code>microservices</code> at the same time for integration testing. <code>codeship-services.yml</code> would have helped if I wanted to build my services serially rather than in parallel. </p>

<p>Is my understanding correct?</p>
",https://stackoverflow.com/questions/46333040/using-docker-compose-vs-codeship-services-in-my-ci-pipeline,"['docker', 'docker-compose', 'microservices', 'codeship']",420,TRUE,3,2
call api Test server : .net core API integration tests,"<p>I Have an API (.net core) and a local application based on Angular. I want to do integration tests for this API without testing it directly by client side. 
I checked the .net core docs and I found this : <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing</a></p>

<p>That's what I've done :</p>

<pre><code>public class Customers
{
    private readonly TestServer _server;
    private readonly HttpClient _client;
    public Customers()
    {
        // Arrange
        _server = new TestServer(new WebHostBuilder().UseStartup&lt;Startup&gt;());
        _client = _server.CreateClient();
    }

    [Fact]
    public async Task ReturnSomething()
    {
        // Act
        var response = await _client.GetAsync(""/api/customers/test"");
        response.EnsureSuccessStatusCode();

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

        // Assert
        Assert.Equal(""test"",
            responseString);
    }
}
</code></pre>

<p>I have this response : Response status code does not indicate success : 500 (internal server error)</p>

<p>When I put ""await _client.GetAsync(""/api/customers/testtttt"" => an incorrect link to API, it display : 404 (not found) so I assume it can join the API.</p>

<p>Why 500 internal error? and how can I have 200 success?</p>

<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/46400824/call-api-test-server-net-core-api-integration-tests,['asp.net-core'],894,TRUE,2,1
aspnet core integration test returning 404,"<p>I'm trying to implement the integration test for my app following the tutorial from: <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing</a></p>

<pre><code>public class CreditCardApplicationShould
{
    [Fact]
    public async Task RenderApplicationForm()
    {
        var builder = new WebHostBuilder()
            .UseContentRoot(@""C:\Users\usuario\source\repos\CreditCardApp\CreditCardApp"")
            .UseEnvironment(""Development"")
            .UseStartup&lt;CreditCardApp.Startup&gt;()
            .UseApplicationInsights();

        var server = new TestServer(builder);

        var client = server.CreateClient();

        var response = await client.GetAsync(""/Apply/Index"");

        response.EnsureSuccessStatusCode();

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

        Assert.Contains(""New Credit Card Application"", responseString);
    }
}
</code></pre>

<p>However, when I'm trying to run the integration test, it gives me the following error:</p>

<blockquote>
  <p>""Message: System.InvalidOperationException : The view 'Index' was not
  found. The following locations were searched:
  /Views/Apply/Index.cshtml /Views/Shared/Index.cshtml""</p>
</blockquote>

<p>It seems to be a common problem when separating the integration test from the MVC application.</p>

<p>Here's the startup.cs too</p>

<pre><code>public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile(""appsettings.json"", optional: false, reloadOnChange: true)
            .AddJsonFile($""appsettings.{env.EnvironmentName}.json"", optional: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();
        CurrentEnvironment = env;
    }

    public IConfiguration Configuration { get; }

    private IHostingEnvironment CurrentEnvironment { get;  }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddApplicationPart(typeof(ApplyController).GetTypeInfo().Assembly);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler(""/Home/Error"");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =&gt;
        {
            routes.MapRoute(
                name: ""default"",
                template: ""{controller=Home}/{action=Index}/{id?}"");
        });
    }
}
</code></pre>

<p>I've found some work arounds, that says to include the AddApplicationPart in the Startup.cs, but it's still not working.</p>

<p>I'm not sure if it's not working because I'm using .NET Core 2.0. I appreciate any tips.</p>
",https://stackoverflow.com/questions/46203001/aspnet-core-integration-test-returning-404,"['c#', 'asp.net-core', '.net-core', 'integration-testing', 'asp.net-core-2.0']",2961,TRUE,7,1
Running different @Sql statements depending on active profile with Spring test,"<p>For integration testing on an application, depending on what we want to test, we have 2 separate spring profiles, one that uses H2 as the embedded database, and another one that uses MySQL embedded as database.
Each profile is called H2 and MYSQL respectively, for our tests we have a common base class called WithJsonItResources, and we want to be able to drop the database after each test is executed, this is how it looks like at the moment:</p>

<pre><code>@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, statements = ""DROP DATABASE mytestdb"")
public abstract class WithJsonItResources extends WithJsonTestResources {
    protected WithJsonItResources(Class resourcesForClass) {
        super(resourcesForClass);
    }
}
</code></pre>

<p>How can I add some sort of validation or whatever, so that if the profile is H2, it runs:</p>

<pre><code>@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, statements = ""DROP ALL OBJECTS DELETE"")
</code></pre>

<p>And if it's the MYSQL profile it runs:</p>

<pre><code>@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, statements = ""DROP DATABASE mytestdb"")
</code></pre>

<p>Thanks!</p>
",https://stackoverflow.com/questions/41962921/running-different-sql-statements-depending-on-active-profile-with-spring-test,"['spring', 'spring-boot', 'spring-data', 'spring-test', 'spring-orm']",855,FALSE,2,1
Posting byte array header with Fiddler,"<p>I have developed a <code>HttpModule</code> that is supposed to <a href=""http://www.haproxy.org/download/1.8/doc/proxy-protocol.txt"" rel=""nofollow noreferrer"">read <code>PROXY V2</code> binary request header</a> and convert it to <code>'X-Forwarded-For'</code></p>

<p>I have been trying to create a request in fiddler that would represent something that looks like <a href=""http://www.haproxy.org/download/1.8/doc/proxy-protocol.txt"" rel=""nofollow noreferrer"">binary PROXY v2 header</a> to do integration testing.</p>

<p>However when I tried adding header decoded from binary </p>

<p><code>Encoding.ASCII.GetString(new byte[12] { 0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A })</code></p>

<blockquote>
  <p>""\r\n\r\n\0\r\nQUIT\n""</p>
</blockquote>

<p>and putting output into Fiddler I got 400 error and request didn't even reach my <code>HttpModule</code> (breakpoints get hit if I remove invalid header - so no configuration problem here)</p>

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

<p>I mean this might not even possible but if it does<br>
<strong>How does one encode data in byte array when sending it with fiddler?</strong> </p>
",https://stackoverflow.com/questions/42432215/posting-byte-array-header-with-fiddler,"['arrays', 'encoding', 'http-headers', 'integration-testing', 'fiddler']",520,FALSE,2,0
Is this possible to write good tests avoiding mocking and &quot;expects&quot; on internal methods?,"<p>Is this possible to avoid mocking in phpunit?</p>

<p>My concept is to:
- write unit tests to test smaller parts
- when it comes to do a integration/functional test then it's possible to inject a null object class using the dependency injection (so it's good to have everything interfaced). But integration tests could be separated from unit tests.</p>

<p>The reason why I don't like the mocking is that I see that its underused in every test, it's totally not readable. I was thinking about separation on unit testing and integration testing.</p>

<p>Could this in most cases be alternative to mocking, or is the mocking not replaceable at all? What's the best practice?</p>
",https://stackoverflow.com/questions/42434833/is-this-possible-to-write-good-tests-avoiding-mocking-and-expects-on-internal,"['php', 'unit-testing', 'phpunit']",79,TRUE,1,1
Suppress static block,"<p><strong>Programming Language : Java<br>
Testing tool         : powermockito,Junit</strong></p>

<p>I have a static block in my code. I am using that code particle as several reference. While during integration testing (using powermockito) I mocked a <code>getWebDetails()</code> method in the below example. The method for mocking (<code>getWebDetails</code>) is also getting called from the static block in my program, so it excecutes before my test gets excecuted and returns a null value. I need to assign values to xml contents during my testing. </p>

<pre><code>class test1{
    private static String xmlcontents;

    static {
        xmlcontents= ServiceUtils.getWebDetails();
    }

    public static String getWebDetails() throws Exception{
        url = test2.getURL();
        return url;
    }
}
</code></pre>

<p>Nota bene (please note): I tried using @SuppressStaticInitializationFor(""test1""), but it suppresses all the static methods inside the class.</p>

<p>Can anyone help me? Any help will be highly appreciable..</p>
",https://stackoverflow.com/questions/44564040/suppress-static-block,"['java', 'junit', 'integration-testing', 'powermockito']",322,FALSE,1,0
Get jmeter functional test code coverage,"<p>I am trying to extract code coverage report on my jmeter functional test execution using maven plugin. I tried using jacoco plugin to get it configured to generate the code coverage report, but it seems to be configurable with only unit and Integration testing which are in format of java classes e.g. *IT.java or *Test.java. But in my case the functional test execution is happening with Jmeter .jmx file with the use of jmeter plugin. I know its little rare to get code coverage for functional tests, but if anyone has worked on a similar thing please share some details. Below is the plugin I am using for Jmeter test execution.</p>

<pre><code>&lt;plugin&gt;
               &lt;groupId&gt;com.lazerycode.jmeter&lt;/groupId&gt;
                   &lt;artifactId&gt;jmeter-maven-plugin&lt;/artifactId&gt;
                   &lt;version&gt;2.1.0&lt;/version&gt; 
                   &lt;executions&gt;
                     &lt;execution&gt;
                              &lt;id&gt;jmeter-tests&lt;/id&gt;
                              &lt;phase&gt;verify&lt;/phase&gt;
                              &lt;goals&gt;
                                &lt;goal&gt;jmeter&lt;/goal&gt;
                              &lt;/goals&gt;
                         &lt;/execution&gt;
                  &lt;/executions&gt; 
                  &lt;configuration&gt;
                    &lt;ignoreResultFailures&gt;true&lt;/ignoreResultFailures&gt;
                    &lt;resultsDirectory&gt;${jmeter-testresults}&lt;/resultsDirectory&gt;
                        &lt;propertiesUser&gt; 
                              &lt;hostname&gt;${jmeter-testhost}&lt;/hostname&gt;
                              &lt;hostport&gt;${jmeter-testport}&lt;/hostport&gt;
                              &lt;testresults&gt;${jmeter-testresults}&lt;/testresults&gt;
                    &lt;/propertiesUser&gt; 
                       &lt;propertiesJMeter&gt;
                              &lt;jmeter.save.saveservice.url&gt;true&lt;/jmeter.save.saveservice.url&gt;
                              &lt;jmeter.save.saveservice.samplerData&gt;true&lt;/jmeter.save.saveservice.samplerData&gt;
                       &lt;/propertiesJMeter&gt; 
              &lt;/configuration&gt;
            &lt;/plugin&gt;
</code></pre>
",https://stackoverflow.com/questions/46711015/get-jmeter-functional-test-code-coverage,"['java', 'jmeter', 'code-coverage', 'maven-plugin', 'jacoco-maven-plugin']",2097,TRUE,1,1
Testing communications software in two different JVMs,"<p>I've written a module in Java that communicates over a socket. I'd like to write a unit test that tests sending and receiving. </p>

<p>To really test the system, I'd like to put the sender in one JVM and the receiver in another and test them together.</p>

<p>From what I've read here and in various blog posts, this isn't really unit testing, it's integration testing. Ok, fine, but I still want it to be part of the build process.</p>

<p>Is there an official, recommended way to launch a second JVM from within a Junit test case? If not, is there another standard testing framework that is designed for this? </p>
",https://stackoverflow.com/questions/42142809/testing-communications-software-in-two-different-jvms,"['java', 'unit-testing', 'junit', 'integration-testing']",26,TRUE,-1,1
Spring Boot / Spring Data integration tests,"<p>Didn't manage to configure Spring Boot for integration testing. Cold you please take a look at the code below:</p>

<p><strong>Entities</strong></p>

<pre><code>@Entity(name = ""Item"")
@Table(name = ""item"")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Getter @Setter @NoArgsConstructor
public class Item extends CoreEntity {

    @Embedded
    protected CurrencyAmount amount;

    @Column(name = ""operation_time"")
    protected ZonedDateTime operationTime;

    @Column(name = ""description"")
    protected String description;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = ""category_id"")
    protected ItemCategory category;

}



@Entity(name = ""Income"")
@Table(name = ""income"")
@Getter @Setter @NoArgsConstructor
public class Income extends Item {

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = ""budget_id"")
    private Budget budget;

    ...

}
</code></pre>

<p><strong>Repository</strong></p>

<pre><code>@Repository(""incomeDao"")
public interface IncomeDao extends JpaRepository&lt;Income, Long&gt; {
}
</code></pre>

<p><strong>Test configuration</strong></p>

<pre><code>@Configuration
@EnableJpaRepositories(basePackages = ""dao.item"")
@EntityScan(basePackages = {""model""})
@PropertySource(""classpath:application.properties"")
@EnableTransactionManagement
public class DaoTestConfiguration {

    @Autowired
    private Environment environment;

    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getProperty(""spring.datasource.driver-class-name""));
        dataSource.setUrl(environment.getProperty(""spring.datasource.url""));
        dataSource.setUsername(environment.getProperty(""spring.datasource.username""));
        dataSource.setPassword(environment.getProperty(""spring.datasource.password""));
        return dataSource;
    }

}
</code></pre>

<p><strong>Application properties</strong></p>

<pre><code>spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
</code></pre>

<p><strong>Test case</strong></p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DaoTestConfiguration.class)
@DataJpaTest
public class IncomeDaoTest {

    @Autowired
    private IncomeDao incomeDao;

    @Test
    public void testSave() {
        Budget budget = Budget.getBulider().setMonth(Month.NOVEMBER).build();
        ItemCategory category = ItemCategory.getBuilder()
                .setItemGroup(ItemGroup.INCOME)
                .setCathegoryName(""Salary"")
                .build();
        Income income = Income.getBuilder()
                .setBudget(budget)
                .setCurrencyAmount(new CurrencyAmount(Currency.getInstance(""USD""), BigDecimal.TEN))
                .setDescription(""Monthly salary"")
                .setItemCategory(category)
                .setOperationTime(ZonedDateTime.of(2017, 1, 12, 12, 0, 0, 0, ZoneId.of(""UTC"")))
                .build();
        incomeDao.save(income);

        assertThat(incomeDao.findAll()).containsExactly(income);
    }
}
</code></pre>

<p>I tried a different configuration (its last edition), but all the time I get the same exception:</p>

<pre><code>Caused by: org.h2.jdbc.JdbcSQLException: Таблица ""INCOME"" не найдена
Table ""INCOME"" not found; SQL statement:
insert into income (model/amount, currency, category_id, description, operation_time, budget_id, id) values (?, ?, ?, ?, ?, ?, ?) [42102-196]
</code></pre>

<p>More over the nature of the exception is strange as the main idea to let spring boot to auto-generate schema according to entity annotations. Thus, at the moment of insertion spring had to create table but looks that it didn't. If someone give an idea what I did wrong or if somebody already faced such an issue - please let me knkow. Thanks.</p>
",https://stackoverflow.com/questions/47539906/spring-boot-spring-data-integration-tests,"['java', 'spring-boot', 'spring-data', 'integration-testing']",1853,TRUE,0,3
Regression testing in rails using rspec,"<p>I know that Rspec is a tool for testing, it covers BDD and TDD in rails,it tests the business logic of application with controller and model tests. My Rails app has almost full coverage (around 85%-90%) with model and controller tests but still someone said that regression testing is not being performed on my application. </p>

<p>I have following concerns regarding rspecs :</p>

<ol>
<li>Can we call combinations of model specs and controllers specs as integration testing? (i think yes but still want to confirm)</li>
<li>Can we call combination of model specs and controller specs as regression testing? </li>
<li>Feature specs written with cypybara can only be considers as regression testing? </li>
</ol>
",https://stackoverflow.com/questions/44551423/regression-testing-in-rails-using-rspec,"['ruby-on-rails', 'capybara', 'integration-testing', 'rspec-rails', 'regression-testing']",982,FALSE,0,1
Why composer install --no-dev does not work?,"<p>I am developing a package library which has regular dependencies and one dev dependency. <a href=""https://getcomposer.org/doc/02-libraries.md#lock-file"" rel=""noreferrer"">Composer recommends to not include the <code>composer.lock</code> file for libraries</a>, so here is the <code>composer.json</code></p>
<pre class=""lang-json prettyprint-override""><code>{
    &quot;name&quot;: &quot;myself/mypackage&quot;,
    &quot;require&quot;: {
        &quot;php&quot;: &quot;&gt;=5.6&quot;,
        &quot;nesbot/carbon&quot;: &quot;~1.20&quot;
    },
    &quot;require-dev&quot;: {
        &quot;phpunit/phpunit&quot;: &quot;^6.0&quot;
    }
}
</code></pre>
<p>I want this to be compatible for use with applications running PHP 5.6, and I want to develop it using the latest PHPUnit testing tools which require PHP 7.</p>
<p>On the travis continuous integration testing server, I have a build matrix which runs the PHPUnit tests on PHP &gt; 7 and a linting script:</p>
<pre><code>composer install
./lint-php.bash
phpunit
</code></pre>
<p>and on PHP &lt; 7, simply lint the source code:</p>
<pre><code>composer install --no-dev
./lint-php.bash
</code></pre>
<p>However, it fails because it ignores the <code>--no-dev</code> flag and tries to install the dev dependency anyway.</p>
<blockquote>
<pre><code>Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - phpunit/phpunit 6.0.7 requires php ^7.0 -&gt; your PHP version (5.6.5) does not satisfy that requirement.
    - phpunit/phpunit 6.0.6 requires php ^7.0 -&gt; your PHP version (5.6.5) does not satisfy that requirement.
    - phpunit/phpunit 6.0.5 requires php ^7.0 -&gt; your PHP version (5.6.5) does not satisfy that requirement.
    - phpunit/phpunit 6.0.4 requires php ^7.0 -&gt; your PHP version (5.6.5) does not satisfy that requirement.
    - phpunit/phpunit 6.0.3 requires php ^7.0 -&gt; your PHP version (5.6.5) does not satisfy that requirement.
    - phpunit/phpunit 6.0.2 requires php ^7.0 -&gt; your PHP version (5.6.5) does not satisfy that requirement.
    - phpunit/phpunit 6.0.1 requires php ^7.0 -&gt; your PHP version (5.6.5) does not satisfy that requirement.
    - phpunit/phpunit 6.0.0 requires php ^7.0 -&gt; your PHP version (5.6.5) does not satisfy that requirement.
    - Installation request for phpunit/phpunit ^6.0 -&gt; satisfiable by phpunit/phpunit[6.0.0, 6.0.1, 6.0.2, 6.0.3, 6.0.4, 6.0.5, 6.0.6, 6.0.7].
</code></pre>
</blockquote>
<p>Why is it ignoring the <code>--no-dev</code> flag? I just want it to install my regular dependencies and to ignore the <code>require-dev</code> section.</p>
",https://stackoverflow.com/questions/42375219/why-composer-install-no-dev-does-not-work,"['php', 'composer-php']",15987,TRUE,8,1
Spring Cloud Contract - how to test simple string response?,"<p>I'm using Spring Cloud Contract framework for REST services integration testing and related client apps contracts. It works for object JSON request / response, but is there a chance to check simple string. Espetially, service which responses Boolean (true or false in response body)?</p>

<p>Part of groovy definition:</p>

<pre><code>response {
    status 200
    headers {
        header('Content-Type', 'application/json;charset=UTF-8')
    }
    body(
        value(client('true'), server(regex(""true|false"")))
    )
}
</code></pre>

<p>Related part of generated test:</p>

<pre><code>    String responseBody = response.getBody().asString();
    null;
</code></pre>

<p>Is it a bug, isn't it? Or should I do something better in groovy definition? First row gives a chance generator understands what I want, but second line is completely out. Thanks for any hint.</p>

<p>P.S. I know there are different opinions about only string ""true"" validity as JSON response (some people says so, other not) Please, don't solve it, but only the real issue :-)</p>
",https://stackoverflow.com/questions/45916752/spring-cloud-contract-how-to-test-simple-string-response,['spring-cloud-contract'],1422,TRUE,2,2
tomcat7-maven-plugin can&#39;t find dependency from reactor,"<p>I have a product line, it has two maven modules: module A and module B</p>

<p>I declare module B depends on module A.</p>

<p>Also I define a maven reactor like this:</p>

<pre><code>    &lt;modules&gt;
        &lt;module&gt;A&lt;/module&gt;
        &lt;module&gt;B&lt;/module&gt;
    &lt;/modules&gt;
</code></pre>

<p>Module A is a pure Java module, Module B is a web module. 
I am trying to do integration testing, so I start tomcat7-maven-plugin 2.0 in Module B.</p>

<p>Embedded tomcat works perfectly If I build and install modules one by one like this : </p>

<pre><code>    cd A
    mvn clean install
    cd ../B
    mvn clean install
</code></pre>

<p>But if I run the reactor, Embedded tomcat will complain class X is not found which is in Module A and fails to start:</p>

<pre><code>    cd reactor
    mvn clean install
</code></pre>

<p>By the way, without tomcat7-maven-plugin, the reactor works well.</p>

<p>my tomcat7-maven-plugin version is 2.0</p>
",https://stackoverflow.com/questions/45088994/tomcat7-maven-plugin-cant-find-dependency-from-reactor,"['java', 'maven', 'tomcat', 'maven-plugin', 'embedded-tomcat-7']",111,TRUE,1,1
What is the minimum test to verify that a component can save/retrieve UTF8 encoded strings,"<p>I am integration testing a component.  The component allows you to save and fetch strings.  </p>

<p>I want to verify that the component is handling UTF-8 characters properly.  What is the minimum test that is required to verify this?</p>

<p>I think that doing something like this is a good start:</p>

<pre><code>// This is the ☺ character
String toSave = ""\u263A"";
int id = 123;

// Saves to Database
myComponent.save( id, toSave );

// Retrieve from Database
String fromComponent = myComponent.retrieve( id );

// Verify they are same 
org.junit.Assert.assertEquals( toSave, fromComponent );
</code></pre>

<p>One mistake I have made in the past is I have set <code>String toSave = ""è""</code>.  My test passed because the string was saved and retrieved properly to/from the DB.  Unfortunately the application was not actually working correctly because the app was using ISO 8859-1 encoding.  This meant that è worked but other characters like ☺ did not.  </p>

<p>Question restated: <em>What is the minimum test (or tests) to verify that I can persist UTF-8 encoded strings?</em></p>
",https://stackoverflow.com/questions/43551397/what-is-the-minimum-test-to-verify-that-a-component-can-save-retrieve-utf8-encod,"['java', 'string', 'encoding', 'utf-8']",323,TRUE,5,3
PCFDEV: Pivotal Network returned: 451 Unavailable For Legal Reasons,"<p>This is an informational post about a recent problem I encountered when installing PCFDEV for use in development and testing. </p>

<p>On Ubuntu-16.04 server core, when I was starting PCFDEV as follows ...</p>

<pre><code>cf dev start
</code></pre>

<p>... I was getting the error ""Pivotal Network returned: 451 Unavailable For Legal Reasons"".</p>

<p>I was using this within the proper terms and conditions (local development and/or integration testing) and my email and password are correct. Why was I getting this error? </p>

<p>Possible Reasons and/or Solutions:</p>

<ol>
<li>Make Sure to Download the most recent version of PCFDEV (<a href=""https://stackoverflow.com/a/44029486/1669464"">https://stackoverflow.com/a/44029486/1669464</a>).</li>
<li>Logging into the Pivotal.io website with the credentials being used may resolve the issue (<a href=""https://stackoverflow.com/a/44094847/1669464"">https://stackoverflow.com/a/44094847/1669464</a>).</li>
</ol>
",https://stackoverflow.com/questions/44029373/pcfdev-pivotal-network-returned-451-unavailable-for-legal-reasons,"['ubuntu-16.04', 'cloud-foundry', 'pcfdev']",96,TRUE,0,2
SpringBoot Test ContextConfiguration has no banner,"<p>I'm writing an integration testing framework, and in my parent test class I have the following:</p>

<pre><code>@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public abstract class IntegrationTestParent extends AbstractTestNGSpringContextTests {

    ...

    @Configuration
    @EnableAutoConfiguration
    @ComponentScan(""redacted"")
    public static class AutomationTestConfig {
    }
}
</code></pre>

<p>Which allows me a great deal of flexibility, however, I've noticed that my custom <code>banner.txt</code> file is no longer printed out, nor is my application.properties file (which sets <code>spring.output.ansi.enabled=ALWAYS</code> and some maven filtered application variables) being read.</p>

<p>In addition to some really leet figlet generated ascii art, it printed out a lot of convenient debug information about the JVM and various system and environment properties so I had a really good idea about the remote environments (a la Jenkins and Bamboo or anyone's arbitrary laptop) they were running on.</p>

<p>Is there a way to get this to behavior in addition to <code>@ContextConfiguration(loader = AnnotationConfigContextLoader.class)</code>? </p>
",https://stackoverflow.com/questions/42660339/springboot-test-contextconfiguration-has-no-banner,"['spring-boot', 'spring-boot-test']",606,TRUE,0,1
"web framework, .. Spring, dropwizard thread pooling and DI","<p>I wanted to understand thread pool operation in web framework . I saw this behavior with Dropwizard, (Spring behavior is also the same).
Say we have defined a resource..</p>

<pre><code>@Path(""/id/create"") 
CreateResource { ...
</code></pre>

<p>then..e.g. for Integration Testing  we have </p>

<pre><code>Thread T1, T2, T3 T4
foreach: Thread // 1 to 4
Call above resource...
</code></pre>

<p>My expectation was that each call to the resource would take a thread from the Thread pool and instantiate a new ""CreateResource"" object. However each call to the resource is on a different Thread form the ThreadPool, as expected. However, I see that the ""CreateResource"" is the same object in each of the 4 API calls. i.e. There is only 1 instance of ""CreateResource"". </p>

<p>why is that so ? </p>

<p>Where can i find more information about this behavior ?</p>
",https://stackoverflow.com/questions/42502149/web-framework-spring-dropwizard-thread-pooling-and-di,"['java', 'spring', 'spring-mvc', 'aop', 'dropwizard']",72,FALSE,0,0
Resolve dynamic path in wireMock,"<p>Hi there I've relativley new to the Wiremock framework. I've got a test enviroment working but I need to for our integration testing need to resolve a dynamic path such as</p>

<p>/test/dynamic/{dynamicpath}/help</p>

<p>where dynamic path is going to be a variable that I want to resolve and then present different data from using a subset of a json file such as</p>

<p>{
  dynamicpathA : ""hello"",
  dynamicpathB ""world""
}</p>

<p>at the moment I have :</p>

<pre><code>    stubFor(get(urlPathMatching(""/test/dynamic/{dynamicpath}/help""))
            .withHeader(""accept"", equalTo(""application/json""))
            .willReturn(aResponse().withBody(readFile(RESOURCES + ""test.json"", Charset.defaultCharset()))));
</code></pre>

<p>which will return an entire json file with the full subset of data but not the individual components in relation to the dynamic uri. My question is there a way to resolve the dynamic url and return dynamic data from the json? </p>

<p>I hope I'm being specific enough I'll update as need be.</p>
",https://stackoverflow.com/questions/43506642/resolve-dynamic-path-in-wiremock,"['java', 'spring', 'wiremock']",7470,FALSE,4,1
Spring-boot datasource commit trouble,"<p>My application uses Spring-Boot 1.4.1.RELEASE and the configuration of my datasource is as follows;</p>

<pre><code>spring:
  datasource:
    url: ***
    username: ***
    password: ***
    driver-class-name: oracle.jdbc.driver.OracleDriver
    initial-size: 1
    max-active: 100
    max-idle: 30
    min-idle: 1
    max-wait: 0
    pool-prepared-statements: true
    max-open-prepared-statements: 3
</code></pre>

<p>The problem is that the last case of my integration testing if it contains a <code>@Sql</code> setup logic in it, fails to commit the last setup SQL. The trouble happens rarely due to the reordering of the cases, and the fact that there is only a handful cases with setup logic to prepare DB. There is no configuration but the one for the OracleDB, and that is in the <code>ConfigClass</code>.</p>

<pre><code>@SpringBootTest(classes = ConfigClass.class)
public class EtcTest {

    @After
    public void teardown() {
        // teardwon X, Y, &amp; Z
    }

    @Test
    @Sql(""setupX.sql"")
    @Sql(""setupY.sql"")
    @Sql(""setupZ.sql"")
    public void get_fromDb() {
        List&lt;Etc&gt; list = buildExpectedList();
        Obj expected = buildExpected();
        Obj actual = getCallToAPI();

        assertThat(rs.getX()).isEqualTo(expected.getX());
        assertThat(rs.getY()).isEqualTo(expected.getY());
        assertThat(rs.getZ()).containsAll(list);
    }
}
</code></pre>

<p>The trouble, for example in the above case if it were the last integration case, 
that it fails to commit the last SQL in the <code>@Sql</code> annotations, namely <code>SetupZ.sql</code>, but the data is not completely missing, it inserts the primary key, and sometimes <code>columnA</code>, or <code>columnB</code>, it is as if something is really wrong here.</p>

<p>Would the presence or absence of some configuration cause this? If not what would be the reason?</p>
",https://stackoverflow.com/questions/42573443/spring-boot-datasource-commit-trouble,"['java', 'spring-boot', 'datasource']",2835,TRUE,22,4
Triggering a pipeline and waiting for it to finish from another pipeline,"<p>I have two different project repositories: my application repository, and an API repository. My application communicates with the API.</p>

<p>I want to set up some integration and E2E tests of my application. The application will need to use the latest version of the API project when running these tests.</p>

<p>The API project is already setup to deploy when triggered</p>

<pre><code>deploy_integration_tests:
  stage: deploy
  script:
  - echo ""deploying...""
  environment:
    name: integration_testing
  only:
    - triggers
</code></pre>

<p>My application has an integration testing job set up like this:</p>

<pre><code>integration_test
  stage: integration_test
  script:
    - echo ""Building and deploying API...""
    - curl.exe -X POST -F token=&lt;token&gt; -F ref=develop &lt;url_for_api_trigger&gt;
    - echo ""Now running the integration test that depends on the API deployment...""
</code></pre>

<p>The problem I am having is that the trigger only queues the API pipeline (both projects are using the same runner) and continues before the API pipeline has actually run.</p>

<p>Is there a way to wait for the API pipeline to run before trying to run the integration test?</p>

<p>I can do something like this:</p>

<pre><code>integration_test_dependency
  stage: integration_test_dependency
  script:
    - echo ""Building and deploying API...""
    - curl.exe -X POST -F token=&lt;token&gt; -F ref=develop &lt;url_for_api_trigger&gt;

integration_test
  stage: integration_test
  script:
    - echo ""Now running the integration test that depends on the API deployment...""
</code></pre>

<p>But that still doesn't grantee that the API pipeline runs and finishes before moving on to the integration_test stage.</p>

<p>Is there a way to do this?</p>
",https://stackoverflow.com/questions/44336447/triggering-a-pipeline-and-waiting-for-it-to-finish-from-another-pipeline,"['gitlab', 'gitlab-ci']",17392,TRUE,17,6
new Builder().forBrowser(&#39;chrome&#39;).build() hangs indefinitely,"<p>I am using mocha and selenium to do end to end integration testing. I am using beforeEach and afterEach hook to initialize browser and kill it after each test. Here is my js file which has both the methods</p>

<pre><code>require('chromedriver')

// globals
global.assert = require('assert')
global.driver = null
const { Builder, By, until, promise } = require('selenium-webdriver')


// setup
beforeEach(async function () {
  this.timeout(utils.DEFAULT_TEST_TIMEOUT)
  while (driver !== null) {
    console.log('waiting for driver to quit from last test')
    await utils.sleep(1000)
  }
  try {
    driver = await new Builder().forBrowser('chrome').build()
    await driver.manage().window().setSize(1600, 900)
  } catch (ex) {
    console.log(ex.stack)
  }

})

afterEach(async function () {
  this.timeout(utils.DEFAULT_TEST_TIMEOUT)
  if (driver === null) {
    console.log('some problem in before each of the test ' + this.currentTest.title + ' returning...')
    return
  }
  await saveScreenShot(SCREENSHOTS_PATH + this.currentTest.parent.title, this.currentTest.title)
  await driver.quit()
  driver = null
})
</code></pre>

<p>Now when i run the test suit on jenkins i very frequently see this (""email already registered"" is a test name)</p>

<pre><code>✓ email domain not allowed (4167ms)
    1) ""before each"" hook for ""email already registered""
some problem in before each of the test email already registered returning...


  39 passing (9m)
  1 pending
  1 failing

  1)  ""before each"" hook for ""email already registered"":
     Error: Timeout of 60000ms exceeded. For async tests and hooks, ensure ""done()"" is called; if returning a Promise, ensure it resolves.
</code></pre>

<p>The thing to notice is that once this error comes the subsequent tests do not run. My test suit has 100s of tests and in the run above it quit once it encountered this beforeEach error and didn't run next set of tests. </p>

<p>I have tried various things but nothing seems to work. Any pointer in debugging this will be very helpful. Thanks in advance.</p>
",https://stackoverflow.com/questions/43875449/new-builder-forbrowserchrome-build-hangs-indefinitely,"['node.js', 'selenium-webdriver', 'mocha.js']",1116,FALSE,3,1
ASP.NET infrastructure in MediatR handlers,"<p>I prefer to keep my handlers free from ASP.NET infrastructure that is very hard to test (yes, even in ASP.NET Core). But sometimes it happens and you have a dependency like UserManager (I'd like to know one day why it's not an interface), HttpContext, etc. and unit-tests are turned into a mocking-hell.</p>

<p>I tried using integration testing to deal with it by creating a TestServer and having all the ASP.NET infrastructure initialized for every api call. It works quite well but sometimes seems like an overkill if I want to  test simple logic of my handler. And while it solves technical problem of mocking ASP.NET infrastructure, it keeps architectural problem (if you consider it so) of having ASP.NET infrastructure into your handlers.</p>

<p>I'd like to know what are the recommended approaches to deal with it?</p>
",https://stackoverflow.com/questions/41931989/asp-net-infrastructure-in-mediatr-handlers,"['asp.net', 'asp.net-web-api', 'asp.net-core', 'mediatr']",1926,TRUE,11,3
Mocking Passport authentication on protected endpoints,"<p>I'm using passport local strategy to authenticate users and I'm having issues with continuous integration testing on protected endpoints. I used <a href=""http://mherman.org/blog/2015/01/31/local-authentication-with-passport-and-express-4/"" rel=""nofollow noreferrer"">this tutorial</a> to get my authentication up and running. I'm using mocha/chai for testing and I can't figure out how to test an endpoint with a user logged during testing. I understand that I may have to use a mock strategy but I'm not sure how to do that. Here is an example endpoint, I need the user to be logged in so that I have access to the req.user.id variable that gets set when I a user is logged in.</p>

<pre><code>router.post('/user/draft/delete', (req, res) =&gt; {
if(!req.user) {
    return res.redirect('/login');
}

User
    .findById(req.user.id)
    .exec()
    .then(user =&gt; {
        user.drafts.pull(req.body.draftid);
        user.save();
        res.status(202).redirect('/dashboard');
    })
    .catch(err =&gt; {
        console.error(err);
        res.status(500).redirect('/dashboard');
    });
});
</code></pre>

<p>I'm not sure what other information might be required but I'm happy to update this post with any code needed.</p>
",https://stackoverflow.com/questions/43574616/mocking-passport-authentication-on-protected-endpoints,"['express', 'mongoose', 'continuous-integration', 'mocha.js', 'passport.js']",227,FALSE,1,0
"How to test API calls (Twitter, Google) and procedural generation","<p>So I've written a twitter bot script that uses mostly API calls to the Twitter API and the Google API (http requests). </p>

<p>The bot:</p>

<ol>
<li>generates some random phrases from local data (Text PCG)</li>
<li>calls google to get a related image</li>
<li>posts everything to twitter</li>
</ol>

<p>If I'd wanted to test this bot automatically what'd be the best approach (best practice) to think about the test suite:</p>

<ul>
<li>Integration testing with a fake HTTP backend</li>
<li>Unit tests for every API call faking some results for the actual HTTP calls</li>
<li>Unit tests that get random data from the PCG modules and fail if said data is not in the spec for what the APIs need (probably unit test without determinism)</li>
<li>Other</li>
</ul>

<p>I'm working in node, in case that's relevant.</p>
",https://stackoverflow.com/questions/47776180/how-to-test-api-calls-twitter-google-and-procedural-generation,"['node.js', 'testing', 'twitter', 'google-api', 'automated-tests']",54,FALSE,1,0
Resolving dependencies in Integration test in ASP.NET Core,"<p>I have ASP.NET Core API. I have already gone through documentation <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""noreferrer"">here</a> that shows how to do integration testing in asp.net core. The example sets up a test server and then invoke controller method.<br>
However I want to test a particular class method directly (not a controller method)? For example:</p>

<pre><code>  public class MyService : IMyService
  {
      private readonly DbContext _dbContext;

      public MyService(DbContext dbContext)
      {
          _dbContext = dbContext;
      }

      public void DoSomething()
      {
          //do something here
      }             
  }
</code></pre>

<p>When the test starts I want <code>startup.cs</code> to be called so all the dependencies will get register. (like dbcontext) but I am not sure in integration test how do I resolve <code>IMyService</code>?</p>

<p>Note: The reason I want to test <code>DoSomething()</code> method directly because this method will not get invoked by any controller. I am using <code>Hangfire</code> inside this API for background processing. The Hangfire's background processing job will call <code>DoSomething()</code> method. So for integration test I want to avoid using Hangfire and just directly call <code>DoSomething()</code> method</p>
",https://stackoverflow.com/questions/43456243/resolving-dependencies-in-integration-test-in-asp-net-core,"['asp.net-core', 'asp.net-core-mvc', 'xunit', 'coreclr']",1834,TRUE,5,1
unit tests in multi module maven project are skipped,"<p><strong>Scenario</strong>: Multi-module Maven project</p>

<p><strong>Issue</strong>: Unit tests are only running for a single module.</p>

<p><strong>Background</strong>:
I'm attempting to separate my integration testing from unit testing.  To do this I've created two properties in my parent pom, <strong>Root-module</strong>, that disable unit tests and integration tests by default.</p>

<pre><code>&lt;maven.test.skip&gt;true&lt;/maven.test.skip&gt;
&lt;maven.integration.test.skip&gt;true&lt;/maven.integration.test.skip&gt;
</code></pre>

<p>In my top-most module, <strong>UI-module</strong>, I've created two profiles, <em>dev</em> and <em>integration-test</em>.  <em>Dev</em> has unit tests enabled and <em>integration-test</em> has integrations enabled:</p>

<pre><code>&lt;profile&gt;
....
&lt;maven.test.skip&gt;false&lt;/maven.test.skip&gt;
&lt;/profile&gt;
</code></pre>

<p><em>Integration-test</em> works correctly.  The <em>dev</em> profile only runs the unit-tests for the <strong>UI-module</strong>, which is where the pom.xml is located that contains these profiles.  </p>

<p>How can I enable unit tests for all modules?  Is the profile approach correct?  If so, why isn't the value applied to other modules?</p>
",https://stackoverflow.com/questions/42989646/unit-tests-in-multi-module-maven-project-are-skipped,"['java', 'maven', 'unit-testing', 'integration-testing', 'maven-module']",402,FALSE,0,0
Can I use rack-test for deployment tests?,"<p>I've built a simple api in <code>Sinatra</code>, with the purpose of setting up a deployment pipeline using <code>Docker</code>. I'm at a stage where I could easily switch <code>Sinatra</code> for something else and there's currently one reason why I might do so.</p>

<p>I once wrote an api using <code>Express</code> and it was trivial to reuse the tests to test a deployment:</p>

<pre><code># Testing the code
chai.request(app)
  .get('/')

# Testing a deployment
chai.request('http://localhost:8080')
  .get('/')
</code></pre>

<p>Examples from: <a href=""https://github.com/chaijs/chai-http#integration-testing"" rel=""nofollow noreferrer"">https://github.com/chaijs/chai-http#integration-testing</a></p>

<p>Now I am wondering if I can accomplish the same with <code>rack-test</code> and <code>Sinatra</code>. Simply sending a URL, instead of the app, crashes. So is there an easy way to accomplish this? I suppose I could write a testing framework on top of <code>rack-test</code>, but I'm not sure it's worth it, even though I do prefer <code>Ruby</code> over <code>Javascript</code> and <code>Sinatra</code> over <code>Express</code>.</p>
",https://stackoverflow.com/questions/42496829/can-i-use-rack-test-for-deployment-tests,"['ruby', 'testing', 'sinatra', 'rack', 'rack-test']",78,TRUE,0,1
Python unittest run TestCases in a specific order,"<p>I have a number of test cases, well say <code>TestA</code>, <code>TestB</code>, <code>TestC</code>, and I want them to be run in a specific order such as <code>TestB</code> --> <code>TestC</code> --> <code>TestA</code>. How can I make sure that the tests are actually run in this order? </p>

<p>Note that those test cases are classes which inherit from <code>unittest.TestCase</code> not just methods inside of a TestCase. That is to say, I am not wondering about the execution order of tests within  a TestCase, I'm wondering about how to change the order in which the TestCase's themselves are run.</p>

<p>For those of you who are going to say that I'm doing something terrible and that's not how you write unit tests, I'm doing integration testing and I am aware this is a bad practice for unit tests.</p>
",https://stackoverflow.com/questions/46554385/python-unittest-run-testcases-in-a-specific-order,"['python', 'python-unittest']",669,TRUE,0,2
Running a rails application inside a gem,"<p>I have a rails application: <code>my_app</code> and it resides within the spec directory of <code>my_gem</code> for integration testing.</p>

<p>Here is the directory structure:</p>

<pre><code>my_gem
|
|--.rspec
|
|-- spec
|    |----support
|    |        |---my_app(rails application)
|    |
|    |----some specs using rspec to test my_app                          
|    |              
|    |----spec_helper                
|    |----rails_helper                  
</code></pre>

<p>my_app is a very basic rails application:</p>

<p>my_app controller:</p>

<pre><code>class MyController &lt; ApplicationController

  def show
    @example = //Model which subclasses active record
    render json: @example
  end

end
</code></pre>

<p>my_app Serializer:</p>

<pre><code>class ExampleSerializer &lt; ActiveModel::Serializer
  attributes :id

end
</code></pre>

<p>my_app behaves as desired if I run it from the root of 'my_app' and all the tests pass when I run rspec.</p>

<p>However,
I have this scenario where I need to run rspec from the root of <code>my_gem</code> to make all the tests run using <code>my_app</code> as well i.e I am trying to run <code>my_app</code> from <code>my_gem</code>. In that case, everything else in <code>my_app</code> runs fine except for the serializers. 
The <code>render json</code> does not serialize the json</p>

<p>My guess is the serializer do not get loaded when I run <code>my_app</code> from the outside  gem. How should I configure my gem to make it run the rails application</p>
",https://stackoverflow.com/questions/43354451/running-a-rails-application-inside-a-gem,"['ruby-on-rails', 'rubygems', 'active-model-serializers']",35,FALSE,2,0
How to properly test php repositories,"<p>I'm trying to write integration tests for my repositories. For simple repositories this seems to be easy. I did something like this </p>

<pre><code>class DBStatusRepositoryTest extends SmBaseIntegrationMemory
{
    private $dbStatusRepository;

    public function setUp()
    {
        parent::setUp();

        $this-&gt;dbStatusRepository = new DBStatusRepository($this-&gt;dbConnection);
    }

    public function testShouldReturnAStatusEntity()
    {
        $status = $this-&gt;dbStatusRepository-&gt;getById(1);
        $this-&gt;assertInstanceOf('Acme\Modules\Foo\Model\Status', $status);
    }
}
</code></pre>

<p>Querying a the status repository should return a status entity.</p>

<p>But I'm not sure how to approach more complex repositories like this one:</p>

<pre><code>public function testAddAttachment()
{
    $itemId = 420807;
    $user = new User([//** data ** //];
    $attachment = new Attachment();
    $attachment-&gt;setUser($user);
    $attachment-&gt;setSomething('something');
    $attachment-&gt;set....;

    $this-&gt;dbAttachmentRepository-&gt;addAttachmentForItem($itemId, $attachment);
    $attchments = $this-&gt;dbAttachmentRepository-&gt;getAllForLead($itemId);
    $this-&gt;assertCount(1, $attchments);
}
</code></pre>

<p>This piece of code is also testing all of the dependencies passed through. I am not sure this is ok.</p>

<p>Also when setting up the repository we could have a tree of dependencies like this:</p>

<pre><code>$userRepository = new DBUserRepository($this-&gt;dbConnection);
$attachmentFactory = new AttachmentFactory($userRepository);
$this-&gt;dbAttachmentRepository = new DBAttachmentRepository($this-&gt;dbConnection, $attachmentFactory);
</code></pre>

<p>Is this the right approach to perform integration testing for repositories?</p>

<p>Update: To be more specific I'm already using DBUnit and in memory sqlite database that is being populated each time a test file runs. However, my question refers to whether is ok to instantiate all the dependencies required for some repository-related operation.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/41889109/how-to-properly-test-php-repositories,"['php', 'integration-testing', 'ddd-repositories']",712,FALSE,2,1
Add columns to all tables in H2 database without manually listing tables,"<p>I have a PostgreSQL database with about 70 tables and I want to add two columns to each of them, <code>created_by</code> and <code>updated_by</code>. Since we're using Liquibase, I have written an update script that works fine in PostgreSQL:</p>

<pre><code>DO $$
DECLARE
  tables CURSOR FOR
    SELECT tablename
    FROM pg_tables
    WHERE schemaname = 'myschema'
    ORDER BY tablename;
BEGIN
  FOR table_record IN tables LOOP
    EXECUTE
      'ALTER TABLE ' || table_record.tablename || ' ADD COLUMN created_by BIGINT; ' ||
      'ALTER TABLE ' || table_record.tablename || ' ADD COLUMN updated_by BIGINT;';
  END LOOP;
END$$;
</code></pre>

<p>However, for integration testing we are using an H2 in-memory database, which doesn't accept this SQL, even in PostgreSQL compatibility mode. <a href=""https://stackoverflow.com/questions/30287369/add-trigger-to-every-table-in-my-h2-database"">From this question</a>, I know how to select all tables:</p>

<pre><code>SELECT * FROM INFORMATION_SCHEMA.TABLES
</code></pre>

<p>but does this work for <code>myschema</code> as well? And is there a way to store the results and loop over them to add the columns? I also don't understand how to use or write prepared statements, as mentioned in the answer.</p>

<p>The basic question is: How can I write an equivalent update script for the H2 database without having to manually list all tables?</p>
",https://stackoverflow.com/questions/46446552/add-columns-to-all-tables-in-h2-database-without-manually-listing-tables,"['sql', 'h2']",1290,FALSE,0,2
How can I allow one package access to another package&#39;s unexported data only when testing?,"<p>In <em>The Go Programming Language</em>, section 11.2.4, there is an example of of an external test accessing <code>fmt.isSpace()</code> via a declaration of <code>IsSpace</code> in <code>fmt</code>'s <code>export_test.go</code> file.  That seemed like the perfect solution, so that's what I did:</p>

<p><code>a/a.go</code>:</p>

<pre><code>package a

var x int

func Set(v int) {
    x = v
}
</code></pre>

<p><code>a/a_test.go</code>:</p>

<pre><code>package a
import ""testing""

func TestSet(t *testing.T) {
    Set(42)
    if x != 42 {
        t.Errorf(""x == %d (expected 42)"", x)
    }
}

func Get() int {
    return x
}
</code></pre>

<p>(Running <code>go test</code> in <code>a/</code> works fine.)</p>

<p><code>b/b.go</code>:</p>

<pre><code>package b
import ""path/to/a""

func CallSet() {
    a.Set(105)
}
</code></pre>

<p><code>b/b_test.go</code></p>

<pre><code>package b
import (
    ""testing""
    ""path/to/a""
)

func TestCallSet(t *testing.T) {
    CallSet()
    if r := a.Get(); r != 105 {
        t.Errorf(""Get() == %d (expected 105)"", r)
    }
}
</code></pre>

<p>Unfortunately, when I run <code>go test</code> in <code>b/</code>, I get:</p>

<pre><code>./b_test.go:11: undefined: a.Get
</code></pre>

<p>Trying to run both sets of test at the same time with <code>go test ./...</code> did not help.</p>

<p>After some considerable poking around I discover that ""<a href=""https://github.com/golang/go/issues/10184"" rel=""nofollow noreferrer"">The *_test.go files are compiled into the package <em>only when running go test for that package</em></a>"" (emphasis mine).  (So, in other words I could access <code>a.Get</code> from an <code>a_test</code> external test package in <code>a/</code>, but not from any package outside of <code>a/</code>.)</p>

<p>Is there some other way I can allow tests from one package to access otherwise-internal data from another package, for integration testing purposes?</p>
",https://stackoverflow.com/questions/42930944/how-can-i-allow-one-package-access-to-another-packages-unexported-data-only-whe,"['testing', 'go', 'integration-testing']",513,TRUE,0,2
How to start a job from another job in a declarative pipeline?,"<p>Lets assume there are two job:</p>

<ol>
<li>a job for a micro-service repository</li>
<li>a job for end-to-end tests</li>
</ol>

<p>I'd like, in specific cases, to start the end-to-end tests job from the micro-service job. For example, after introducing a change that even though passed unit testing and integration testing, it needs further testing, available in the end-to-end tests job.</p>

<p>I'd like for the developers to make a commit with a specific phrase. To that end, I implemented the following in the micro-service pipeline:</p>

<pre><code>pipeline {
    ...
    ...
    stages {
        ...
    }    


    post {
        success {
            if (BRANCH_NAME == ""develop"") {
                result = sh (script: ""git log -1 | grep '.*\\[e2e\\].*'"", returnStatus: true) 
                if (result == 0) {
                    build job: '****', wait: false
                }
            }
        }
    ...
    ...
    }
}
</code></pre>

<p>This seemingly works, as I see the following in the log:</p>

<blockquote>
  <p>git log -1<br>
  grep '.<em>[e2e].</em>'<br>
      Run tests [e2e] [Pipeline] build (Building ****)<br>
  Scheduling item: ****</p>
</blockquote>

<p>So it found ""[e2e]"" and supposedly scheduled a build in the end-to-end tests job, but in actuality nothing happened - no job was scheduled/run.</p>
",https://stackoverflow.com/questions/43375243/how-to-start-a-job-from-another-job-in-a-declarative-pipeline,"['jenkins', 'jenkins-pipeline', 'declarative']",2658,TRUE,3,1
Test integration .Net Core with TestServer return 404 not found?,"<p>I'm trying to create a Integration Test project , for test my web api .Net Core with the Microsoft sample best practice here <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing</a>
But i don't know why, i always get a error message [404 not found], the HttpClient can't find the 'testServer' . And i'm sure my 'route' is right [""api/Registration/"" + guid] , if i try on debug mode from iisexpress. it's work great</p>

<p>If someone have some idea to fix it, will be very gratefull. Thanks</p>

<p>Here is the code i use in my Integration Test project:</p>

<p><strong>RegistrationIntegrationTest.cs:</strong></p>

<pre><code>[TestClass]
public class RegistrationIntegrationTest
{
    private static TestServer server;
    private static HttpClient client;

    [ClassInitialize]
    public static void ClassInitialize(TestContext context)
    {
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var projectPath = Path.GetFullPath(Path.Combine(basePath, ""../../../../Registration""));

        var builder = new WebHostBuilder()
            .UseContentRoot(projectPath)
            .UseEnvironment(EnvironmentName.Development)
            .UseStartup&lt;Startup&gt;();

        server = new TestServer(builder);
        client = server.CreateClient();
    }

    private async Task&lt;string&gt; GetRegistrationResponse(string guid)
    {
        var request = ""api/Registration/"" + guid;

        var response = await client.GetAsync(request);
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsStringAsync();
    }

    [TestMethod]
    public async Task GetRegistration()
    {
        // Act
        var responseString = await GetRegistrationResponse(""A5A3CBFD-8B61-E711-80E2-00505693113A"");
        // Assert
        Assert.Equals(""test"",
            responseString);
    }
}
</code></pre>

<p>And here is my startup Class from my Integration Test project:</p>

<p><strong>Startup.cs</strong></p>

<pre><code>public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            //.AddJsonFile(""appsettings.json"", optional: false, reloadOnChange: true)
            //.AddJsonFile($""appsettings.{env.EnvironmentName}.json"", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddCors();
        services.AddAntiforgery();
        services.AddSingleton&lt;IControllerActivator&gt;(new SimpleInjectorControllerActivator(this.Container));
        services.Configure&lt;MyAppSettings&gt;(Configuration);
        services.UseSimpleInjectorAspNetRequestScoping(this.Container);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection(""Logging""));

        if (env.IsDevelopment())
        {
            loggerFactory.AddDebug();
            app.UseCors(builder =&gt; builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        }
        else if (env.IsStaging())
        {
            app.UseCors(builder =&gt; builder.WithOrigins(""https://apitest.swisscaution.ch""));
        }
        else if (env.IsProduction())
        {
            app.UseCors(builder =&gt; builder.WithOrigins(""https://internalapi.swisscaution.ch""));
        }
        else
        {
            throw new InvalidOperationException(""Bad application environement."");
        }

        app.UseMvc();

        this.InitializeContainer(app);
    }
</code></pre>

<p>Here is a photo of the architecture of my solution Visual Studio,
as you can see, the integration test project is separate from my web api project called 'registration'
<a href=""https://i.stack.imgur.com/KM6v5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/KM6v5.png"" alt=""enter image description here""></a></p>

<p>The Exception i get:
<a href=""https://i.stack.imgur.com/a5wnY.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/a5wnY.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/44962904/test-integration-net-core-with-testserver-return-404-not-found,"['.net', 'unit-testing', 'asp.net-core', 'integration-testing', 'httpclient']",3145,TRUE,2,1
Entity Framework Core - Execute raw sql - Same code for SQL/SQLite,"<p>I'm currently using two different Connections types, (SQLConnection for normal use and SqliteConnection for integration testing), when inserting new exceptions in my LogService.</p>

<p>Because I don't have access to the database context class I'll have to use raw sql to insert new entities, (I only have the database connectionstring).</p>

<p>When running integration tests I have to use SQLite in memory database because of the entity relations, (SQL does not support this in memory).</p>

<pre><code>protected async Task InsertException(DateTime utcNow, LogLevel logLevel, EventId eventId, string state, Exception exception, CategoryAppSettings categoryAppSettings, string caller, string ipAddress, int? userId, int? organisationId, string requestId)
{
    string stackTrace = exception?.StackTrace;

    string query =
        ""INSERT INTO [Exception] "" +
        ""("" +
            ""[Created]"" +
            "",[EventId]"" +
            "",[IpAddress]"" +
            "",[LogLevel]"" +
            "",[Message]"" +
            "",[Source]"" +
            "",[StackTrace]"" +
            "",[State]"" +
            "",[UserId]"" +
            "",[OrganisationId]"" +
            "",[RequestId]"" +
        "")"" +
        ""VALUES"" +
        ""("" +
            ""@Created"" +
            "",@EventId"" +
            "",@IpAddress"" +
            "",@LogLevel"" +
            "",@Message"" +
            "",@Source"" +
            "",@StackTrace"" +
            "",@State"" +
            "",@UserId"" +
            "",@OrganisationId"" +
            "",@RequestId"" +
        "")"";

    Dictionary&lt;string, object&gt; parameters = new Dictionary&lt;string, object&gt;
    {
        { ""@Created"", utcNow },
        { ""@EventId"", eventId.ToString() ?? (object)DBNull.Value },
        { ""@IpAddress"", ipAddress ?? (object)DBNull.Value },
        { ""@LogLevel"", logLevel.ToString() ?? (object)DBNull.Value },
        { ""@Message"", exception?.Message ?? (object)DBNull.Value },
        { ""@Source"", caller ?? (object)DBNull.Value },
        { ""@StackTrace"", stackTrace?.Trim() ?? (object)DBNull.Value },
        { ""@State"", state ?? (object)DBNull.Value },
        { ""@UserId"", userId ?? (object)DBNull.Value },
        { ""@OrganisationId"", organisationId ?? (object)DBNull.Value },
        { ""@RequestId"", requestId ?? (object)DBNull.Value },
    };
    try
    {
        if (_hostingEnvironment.EnvironmentName == ""Test"")
        {
            using (SqliteConnection sqlConnection = new SqliteConnection($""Data Source={_logAppSettings.ConnectionStrings.Database};Mode=Memory;Cache=Shared;""))
            {
                using (SqliteCommand sqlCommand = new SqliteCommand(query, sqlConnection))
                {
                    foreach (var parameter in parameters)
                    {
                        sqlCommand.Parameters.Add(new SqliteParameter(parameter.Key, parameter.Value));
                    }

                    sqlConnection.Open();

                    await sqlCommand.ExecuteNonQueryAsync();
                }
            }
        }
        else
        {
            using (SqlConnection sqlConnection = new SqlConnection(_logAppSettings.ConnectionStrings.Database))
            {
                using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
                {
                    foreach (var parameter in parameters)
                    {
                        sqlCommand.Parameters.Add(new SqlParameter(parameter.Key, parameter.Value));
                    }

                    sqlConnection.Open();

                    await sqlCommand.ExecuteNonQueryAsync();
                }
            }
        }
    }
    catch (Exception ex)
    {
        ExceptionModel exceptionModel = new ExceptionModel()
        {
            StackTrace = ex?.StackTrace,
            Message = ex?.Message,
            InnerException = ex?.InnerException.ToString()
        };

        LogModel log = new LogModel()
        {
            Created = $""{utcNow:yyyy-MM-dd HH:mm}"",
            LogLevel = LogLevel.Error.ToString(),
            EventId = LogEvents.Log,
            Source = ex.Source,
            IpAddress = ipAddress,
            UserId = userId,
            OrganisationId = organisationId,
            State = ""An unexpected error occured while trying to insert new exception."",
            Exception = exceptionModel,
            RequestId = requestId
        };

        InsertLog(utcNow, log, categoryAppSettings);
    }
}
</code></pre>

<p>As you can see I'm using two different database types, two different connection types. I really don't like it when you have to customize your code just to make the test greens!</p>

<p><strong>Is it possible to have one connection type for both databases?</strong></p>

<p>I've looked at ""Entity SQL"" but I don't think it's supported in Entity Framework Core and it's abit legacy-ish..</p>
",https://stackoverflow.com/questions/46308868/entity-framework-core-execute-raw-sql-same-code-for-sql-sqlite,"['c#', 'sql', '.net', 'sqlite', 'entity-framework-core']",1174,TRUE,2,1
System tests VS integration tests Rails 5.1?,"<p>Before upgrading to rails 5.1 i test my rails app via integration tests. And 70% of my rails app is automated via integration tests. Means all of application simple and complex behaviors are automated via integration tests. Off-course rails did not provided any java-script based testing. </p>

<p>With Arrival of Rails 5.1 they include system tests and said that every app interact with java-script and now you can test your app end to end scenarios like a real user interacting with browser. <strong>So my manager ask me to move all integration tests to system tests</strong>. Ok good! we can test our application the way our users experience it and help us test JavaScript as well. </p>

<p>Definitely system test can cover almost all integration tests as well. <strong>So whats the importance of integration testing now ?</strong> </p>

<blockquote>
  <p>Why should someone write integration test in Rails 5.1 when he can
  write same test case in System test?</p>
</blockquote>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/44963659/system-tests-vs-integration-tests-rails-5-1,"['ruby-on-rails', 'ruby-on-rails-5.1']",982,TRUE,10,1
get_CurrentTransaction in InMemory.TransactionManager does not have an implementation,"<p>I'm working on a .NET Core application that implements the InMemoryDatabase for integration testing. I'm following the instructions from <a href=""https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing"" rel=""nofollow noreferrer"">this link</a>. </p>

<p>Basically it shows how to configure the service (in Startup.cs) using the AddDbContext method which is what I did and I make the call to UseInMemoryDatabase:</p>

<pre><code>    public void ConfigureServices(IServiceCollection services)
    {        
        services.AddDbContext&lt;AppDbContext&gt;(options =&gt; options.UseInMemoryDatabase());

        services.AddMvc();

        services.AddSingleton&lt;ITodoRepository, TodoRepository&gt;();
        services.AddScoped&lt;IAssetRepository, AssetRepository&gt;();
    }
</code></pre>

<p>My AppDbContext is defined in another project in the solution and is defined as such:</p>

<pre><code>public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; dbContextOptions) :
        base(dbContextOptions)
    {            
    }

    public DbSet&lt;Asset&gt; Assets { get; set; }
    public DbSet&lt;TodoItem&gt; Todos { get; set; }
}
</code></pre>

<p>Back to the Startup.cs file, according to the link I need to code the Configure method like this:</p>

<pre><code>    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection(""Logging""));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            var repository = app.ApplicationServices.GetService&lt;IAssetRepository&gt;();
            InitializeDatabaseAsync(repository).Wait();
        }

        app.UseStaticFiles();

        app.UseMvc(routes =&gt;
        {
            routes.MapRoute(
                name: ""default"",
                template: ""{controller=Home}/{action=Index}/{id?}"");
        });
    }
</code></pre>

<p>This snippet runs ok and executes the call to GetService. This call runs the constructor for AppDbContext but the constructor crashes with the folling exception. It crashes when calling the base constructor: base(dbContextOptions).</p>

<blockquote>
  <p>Method 'get_CurrentTransaction' in type
  'Microsoft.EntityFrameworkCore.Storage.Internal.InMemoryTransactionManager'
  from assembly 'Microsoft.EntityFrameworkCore.InMemory,
  Version=1.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
  does not have an implementation.</p>
</blockquote>

<p>I can't seem to figure out what is causing this exception. Can someone give me some direction?</p>

<p>Thanks !</p>
",https://stackoverflow.com/questions/42381618/get-currenttransaction-in-inmemory-transactionmanager-does-not-have-an-implement,"['entity-framework', 'asp.net-core']",955,TRUE,2,1
What does Dagger do? Explain in words that an high-school Java programmer can understand,"<p>It is based on the Java Specification Request (JSR) 330. It uses code generation and is based on annotations. The generated code is very relatively easy to read and debug.</p>

<p>1) Dagger provide simplifies access to shared instances
- That means If we declare @Inject annotation in our code then we can get reference everywhere in our projects</p>

<p>2) Easy configuration of complex dependencies</p>

<ul>
<li><p>dagger follow the implicit order and generate Objects so in dependency and generated code both are easy to understand and traced and we can reduce large boilerplate of code,</p></li>
<li><p>normally we can hand to obtain reference and pass them to other objects so we can focus on modules the build rather then focusing the order in which they need to be created</p></li>
</ul>

<p>3) Easier unit and integration testing Because  dependency graph is created for us so its easily swap out module,network response</p>
",https://stackoverflow.com/questions/41604234/what-does-dagger-do-explain-in-words-that-an-high-school-java-programmer-can-un,['android'],51,FALSE,2,0
"Running Traditional, Non-UI Unit Tests in XTC","<p>My team has a battery of traditional, non-ui tests for a Xamarin application. We'd like to run these tests in the XTC but haven't found much documentation about running traditional tests in the XTC.</p>

<p>My best guess is to load our Xamarin Unit Test app into the cloud and then use the UI controls to run and check our unit tests in this app. Is there a more straight forward way that I'm missing?</p>

<p>And again, just to be clear, we don't want to UI test our app directly. We've architected from the ground up using IOC so that we get about 95% test coverage without full integration testing.</p>

<p>For example, here's one of our tests:</p>

<pre><code>[Test]
public void ExecuteThreadSafeActionThrowsNoException()
{
    var test = new List&lt;int&gt; { 1, 2, 3 };

    Assert.DoesNotThrow(() =&gt;
    {
        _concurrent.ExecuteThreadSafe(() =&gt;
        {
            test.Add(4);

            foreach (var i in test)
            {
                Task.Delay(DelayTime).Wait();
            }

            test.Add(5);
        });
    });
}
</code></pre>

<p>Where _concurrent is an interface that has different implementations depending on Platform (iOS and Android) and OS version. All this tests is that our threading code works as expected on multiple devices.</p>
",https://stackoverflow.com/questions/41472766/running-traditional-non-ui-unit-tests-in-xtc,"['ios', 'unit-testing', 'xamarin', 'xamarin-test-cloud']",110,FALSE,1,0
Service dependent on other services - wercker ci,"<p>I'm using wercker to automate test and deploy of an API client by running the API server as a private service alongside redis and postgres services (all application level) for integration testing of the client. This setup theoretically allows my client to interact with the api server and for both the client and server to be able to use the same postgres and redis services. </p>

<p>My private service is dependent on the database services and therefore needs the host and port of those services (exposed environment variables) injected as environment variables into its container at start up. However, I've been unable to access these exposed connection variables from within the same service block that they're declared. </p>

<p>I've posted a section of my wercker.yml below:</p>

<pre><code> - id: postgres
   env:
       POSTGRES_PASSWORD: $POSTGRES_PASSWORD
       POSTGRES_USER: $POSTGRES_USER
       POSTGRES_DB: $POSTGRES_DB

 - redis

 # - spotify/cassandra

 - name: realtime
   id: quay.io/ndustrialio/realtime-api-service
   username: $QUAY_USERNAME
   password: $QUAY_PASSWORD
   tag: latest
   registry: https://quay.io
   env:
       CLIENT_ID: $CLIENT_ID
       CLIENT_SECRET: $CLIENT_SECRET
       POSTGRES_USER: $POSTGRES_USER
       POSTGRES_PASSWORD: $POSTGRES_PASSWORD
       POSTGRES_DB: $POSTGRES_DB
       POSTGRES_HOST: $POSTGRES_PORT_5432_TCP_ADDR
       NODE_ENV: wercker_test
       REDIS_HOST: $REDIS_PORT_6379_TCP_ADDR
       REDIS_PORT: 6379
       REDIS_DB: 0
       CASSANDRA_HOSTS: cassandra
</code></pre>

<p>The environment variables $REDIS_PORT_6379_TCP_ADDR and $POSTGRES_PORT_5432_TCP_ADDR are empty in the realtime service container. How can I access these variables in my realtime service?</p>
",https://stackoverflow.com/questions/45109272/service-dependent-on-other-services-wercker-ci,"['continuous-integration', 'integration-testing', 'wercker']",113,FALSE,1,1
How to call a function which accepts IFormFile without using Mocking framework,"<p>I am trying to call a controller which looks like below:</p>

<pre><code>Task&lt;IActionResult&gt; Create(List&lt;IFormFile&gt; RunFiles)
</code></pre>

<p>Now, I am just trying to figure out what is the easiest way to pass it that list of <code>IFormFiles</code></p>

<pre><code>var formData = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(File.ReadAllBytes(""\\run1\\IHW01018Exp049HLAMicro_S13_L001_R1_001.fastq.gz""));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue(""attachment"")
{
    FileName = ""Fastq.fastq""
};

formData.Add(fileContent, ""FastQ"");

var response = await client.PostAsync($""run"", formData);
</code></pre>

<p>I thought this would at least be recognized as a valid <code>IFormfile</code> but what is happening here is basically, it is calling the method without throwing any errors. However, <code>RunFiles</code> parameters has 0 members. So basically an emptylist of <code>IFormFile</code>.</p>

<p>I looked around web and came across this post :</p>

<p><a href=""https://stackoverflow.com/questions/36858542/how-to-mock-an-iformfile-for-a-unit-integration-test-in-asp-net-core-1-mvc-6"">How to mock an IFormFile for a unit/integration test in ASP.NET Core 1 MVC 6?</a></p>

<p>Which basically suggested to use Moq.Well, guess what, we do not have Moq in our framework. However, it brings  me back to my original question that is there any way to call function like this for UnitTesting/Integration Testing without relying on external frameworks like MOQ? Or am I doing something wrong in existing code?</p>
",https://stackoverflow.com/questions/43990529/how-to-call-a-function-which-accepts-iformfile-without-using-mocking-framework,"['c#', 'unit-testing', 'asp.net-core', 'iformfile']",913,FALSE,1,0
Send GPS Shield data to GPRS Shiled (Sim900),"<p>I'm working on a vehicle telemetry project. For that I was trying to get GPS data from a GPS shield and send them to thingspeak using Sim900 GSM/GPRS shield Get command. The board I am using is a Arduino Uno.</p>

<p>The problem was the GSM/GPRS shield I was using works only with 4800 baud rate, when it uses http. And my GPS is working with 9600 baud rate. I was working with the both shields and in separate operations both(GSM/GPRS along and GPS along) devices work nice. In integration testing (when attaching the both shields to Arduino Uno) GPS data is not sending to thingspeak through GSM/GPRS shield. Also I try to get GPS data in side the code. It didn't work for me! The code is below.</p>

<p>PS - I read the old post under the same topic, but AltSoftSerial is not working for me.</p>

<pre><code>#include &lt;SoftwareSerial.h&gt;
#include &lt;String.h&gt;
#include ""TinyGPS++.h""

int fixed = 0;
int led = 13;
TinyGPSPlus gps;
SoftwareSerial mySerial(4, 5); //GSM
SoftwareSerial SoftSerial(2, 3); //GPS
float longi = gps.location.lng();
float lati = gps.location.lat();


void setup() {
  SoftSerial.begin(9600); //Start GPS
  mySerial.begin(4800); //Start GSM
  Serial.begin(4800); //Start Serial Monitor
  delay(10000);
}

void loop() {
  longi = gps.location.lng();
  lati = gps.location.lat();
  GPSCord();
  Send2Think();


  if(mySerial.available()){
    Serial.write(mySerial.read());
  }
}

void Send2Think(){



  mySerial.println(""AT"");
  delay(500);
  //SoftSerial.println(""HELLO"");

  mySerial.println(""AT+CPIN?"");
  delay(500);
  //SoftSerial.println(""HELLO"");

  mySerial.println(""AT+CREG?"");
  delay(500);

  mySerial.println(""AT+CGATT?"");
  delay(500);

  mySerial.println(""AT+CIPSHUT"");
  delay(500);

  mySerial.println(""AT+CIPSTATUS"");
  delay(500);

  mySerial.println(""AT+CIPMUX=0"");
  delay(500);

  ShowSerialData();

  mySerial.println(""AT+CSTT=\""hutch3g\"""");//start task and setting the APN,
  delay(1000);
  SoftSerial.println(""HELLO"");

  ShowSerialData();

  mySerial.println(""AT+CIICR"");//bring up wireless connection
  delay(3000);

  ShowSerialData();

  mySerial.println(""AT+CIFSR"");//get local IP adress
  delay(2000);

  ShowSerialData();

  mySerial.println(""AT+CIPSPRT=0"");
  delay(3000);

  ShowSerialData();

  mySerial.println(""AT+CIPSTART=\""TCP\"",\""api.thingspeak.com\"",\""80\"""");//start up the connection
  delay(6000);

  ShowSerialData();

  mySerial.println(""AT+CIPSEND"");//begin send data to remote server
  delay(4000);
  ShowSerialData();

  String str1=""GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&amp;field2="" + String(lati)+ ""&amp;field3="" + String(longi);
  mySerial.println(str1);//begin send data to remote server

  delay(4000);
  ShowSerialData();

  mySerial.println((char)26);//sending
  delay(5000);//waitting for reply, important! the time is base on the condition of internet 
  mySerial.println();
  ShowSerialData();

  mySerial.println(""AT+CIPSHUT"");//close the connection
  delay(100);
  ShowSerialData();
}

void ShowSerialData()
{
  while(mySerial.available()!=0)
    Serial.write(mySerial.read());
}

void GPSCord(){
  while (SoftSerial.available() &gt; 0)
  gps.encode(SoftSerial.read());

  if (gps.location.isUpdated())
  {
    fixed = 1;
    Serial.print(""LAT=""); Serial.print(gps.location.lat(), 6);
    Serial.print("" LNG=""); Serial.println(gps.location.lng(), 6);
  }

  if(fixed ==0)
  {
     digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
     delay(300);               // wait for a second
     digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
     delay(300);  
  }
  if (gps.altitude.isUpdated())
  {
    Serial.print(""Altitude:"");
    Serial.println(gps.altitude.meters());
  }
}
</code></pre>
",https://stackoverflow.com/questions/44609109/send-gps-shield-data-to-gprs-shiled-sim900,"['gps', 'arduino-uno', 'gsm', 'sim900']",586,FALSE,0,0
How to rollback all changes in MySQL database with Spring Boot,"<p>I have a Spring MVC Application developed with Spring Boot. This is application is just for learning purposes, by the way.</p>

<p>By default, the app launches and uses a MySQL database. For unit and integration testing, I use an in-memory H2 database and it works perfectly.</p>

<p>Now, for UAT, it's required to have another MySQL database. So, in this new database, I've inserted enough data for the application to work properly, but each time the application runs under UAT profile, it's populated with data that I have to clean manually or restore from a sql file.</p>

<p>I have to 2 profiles. First, it's the production profile:</p>

<pre><code>spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost/dbprod
spring.datasource.username = root
spring.datasource.password = mysql

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
</code></pre>

<p>Second, it's the uat profile:</p>

<pre><code>spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost/dbuat
spring.datasource.username = root
spring.datasource.password = mysql

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
</code></pre>

<p>My question is then how to tell Spring that under UAT profile it should discard all changes that were made (inserts, updates and deletes) . It would be nice if this could be done in the application-uat.properties file</p>
",https://stackoverflow.com/questions/46479601/how-to-rollback-all-changes-in-mysql-database-with-spring-boot,"['mysql', 'spring', 'spring-boot', 'properties-file']",806,TRUE,0,1
Managing version numbers in a custom Gradle Plugin,"<p>I'm developing a custom gradle plugin. At the top of the <code>build.gradle</code> file of the plugin I specify the plugin's version number:</p>

<p><code>version '0.1.3'</code></p>

<p>I have a number of Gradle projects that I use during my custom plugin's unit and integration testing phase. For each of these projects, I have to declare my custom plugin's jar as a dependency in the project's <code>build.gradle</code> file . For example:</p>

<p><code>classpath files('libs/UmpleGradlePlugin-0.1.3.jar')</code></p>

<p>Ideally, I'd have the version number written in one place rather than explictly writing it in every test project I use. To that end, I've created a constants file, <code>Constants.java</code>, that includes <code>static final string VERSION_NUMBER = ""0.1.3""</code>. I want to use <code>VERSION_NUMBER</code> in the build files of my projects rather than rather than writing the version number explicitly. </p>

<p>I've compiled <code>Constants.java</code> and added <code>Constants.class</code> to the <code>classpath</code>. However, when I try to use <code>Constants.VERSION_NUMBER</code> in a <code>build.gradle</code> file, Gradle thinks I'm trying to use a property that doesn't exist:</p>

<p><code>FAILURE: Build failed with an exception. Could not find property 'Constants' on root project 'UmpleGradlePlugin'.</code></p>

<p>How can I use <code>VERSION_NUMBER</code> in a build file?</p>
",https://stackoverflow.com/questions/42800978/managing-version-numbers-in-a-custom-gradle-plugin,['gradle'],142,TRUE,0,1
How to force Spring Data Jpa to read entity from db tables in all test scenarios?,"<p>I want to perform Integration testing of Spring Data Jpa repositories.
For example I have an Entity with <code>@Column(updatable = false)</code> and want to make sure it will not be updated if I will try.</p>

<p>What i do is:</p>

<pre><code>MyEntity ent = repo.findById(id);
assert ent.getNotUpdatableField == true;
ent.setNotUpdatableField(false);
repo.saveAndFlush(ent);
MyEntity updatedEnt = repo.findById(id);
assert ent.getNotUpdatableField == true;
</code></pre>

<p>The last assertion fails because of for the second time repository returns literally the same object which was returned for the 1st time and was assigned to <code>ent</code> variable.
But the field was not actually updated in database and no exception was raised.</p>

<p>To test what I want to test I found a solution to autowire <code>EntityManager</code> and call either <code>.clear()</code> or <code>refresh(ent)</code> on it after <code>saveAndFlush(ent)</code>.
I would like to know if it is possible to force repositories to load data from tables in <strong>all</strong> tests? Manual usage of <code>@Autowired</code> <code>EntityManager</code> in each scenario is tedious.</p>

<p>Probably I do something wrong at all an there are even better ways to test Spring Data JPA entities.</p>
",https://stackoverflow.com/questions/46104669/how-to-force-spring-data-jpa-to-read-entity-from-db-tables-in-all-test-scenarios,"['spring', 'hibernate', 'jpa', 'spring-data-jpa']",1244,FALSE,0,0
Creating stub for interface in .net core,"<p>I am in the process of porting existing code from .net 4.0 to .net core 2.0. The current solution is a WCF service, unit tests and a stub (for third party). The WCF service has been rewritten as a .net core RESTful API and the unit tests are being developed to work with this.</p>

<p>I need to be able to provide a mechanism for development environments to be able to use the new API for integration testing and these means communication between the API and another service. Historically, we have simply setup a standard website and exposed an .asmx that implements the interface;</p>

<pre><code>public class AutoId : System.Web.Services.WebService, IIdentificationService_1_1Soap
{
}
</code></pre>

<p>Without adding an old style web application, which I can then add an .asmx to, I am not sure how I can achieve this. I am led to believe the .asmx and wcf services in the .net core world are dirty words, so how can I expose this interface (not consume it) in .net core?</p>
",https://stackoverflow.com/questions/46644447/creating-stub-for-interface-in-net-core,"['c#', '.net', 'soap', 'asp.net-core']",548,FALSE,2,0
Spring Data Rest resource processing failure,"<p>I'm attempting to use Spring Data Rest resource processors to add a link to a resource; however, during <code>MockMvc</code> integration testing, it blows up with a class cast exception, complaining that an <code>EmptyCollectionEmbeddedWrapper</code> cannot be converted to <code>ResourceSupport</code> (the bounds of the <code>ResourceProcessor</code>'s parameterized type):</p>

<pre><code>java.lang.ClassCastException: org.springframework.hateoas.core.EmbeddedWrappers$EmptyCollectionEmbeddedWrapper cannot be cast to org.springframework.hateoas.ResourceSupport
    at org.springframework.data.rest.webmvc.ResourceProcessorInvoker$DefaultProcessorWrapper.invokeProcessor(ResourceProcessorInvoker.java:225) ~[spring-data-rest-webmvc-2.5.3.RELEASE.jar:na]
    at org.springframework.data.rest.webmvc.ResourceProcessorInvoker.invokeProcessorsFor(ResourceProcessorInvoker.java:142) ~[spring-data-rest-webmvc-2.5.3.RELEASE.jar:na]
    at org.springframework.data.rest.webmvc.ResourceProcessorInvoker.invokeProcessorsFor(ResourceProcessorInvoker.java:119) ~[spring-data-rest-webmvc-2.5.3.RELEASE.jar:na]
    at org.springframework.data.rest.webmvc.ResourceProcessorHandlerMethodReturnValueHandler.handleReturnValue(ResourceProcessorHandlerMethodReturnValueHandler.java:114) ~[spring-data-rest-webmvc-2.5.3.RELEASE.jar:na]
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:130) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) [spring-test-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) [spring-test-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155) [spring-test-4.3.3.RELEASE.jar:4.3.3.RELEASE]
</code></pre>

<p>It's expected that the returned value should be empty at this point (as <code>EmptyCollectionEmbeddedWrapper</code> suggests), but of course the class cast is not intended. As the stack trace suggests, this exception occurs during resource post processing; if I remove a simple resource processor I have for this type, the class cast exception disappears and the request succeeds. This is surprising to me, because the resource processor is essentially lifted from the documentation. </p>

<p>In more detail, the resource parameter type is <code>Notification</code>; the <code>MockMvc</code> request that fails looks like:  </p>

<pre><code>perform(get(entityLinks.linkToSearchResource(Notification.class, NotificationRepository.ACTIVE_SEARCH)
            .expand(Collections.singletonMap(""projectId"", 1)).getHref()))
            .andExpect(status().isOk())
            .andExpect(jsonPath(""$._embedded.notifications"").isEmpty());
</code></pre>

<p>And the <code>ResourceProcessor</code> looks like:</p>

<pre><code>@Bean
public ResourceProcessor&lt;Resource&lt;Notification&gt;&gt; notificationResourceProcessor(RepositoryEntityLinks entityLinks) {
    return notificationResource -&gt; {
        notificationResource.add(entityLinks.linkToCollectionResource(NotificationAction.class));
        return notificationResource;
    };
}
</code></pre>

<p>I assume I've got something misconfigured, because this seems like a very basic usage of Spring Data Rest. What am I missing?</p>
",https://stackoverflow.com/questions/44229990/spring-data-rest-resource-processing-failure,"['java', 'spring', 'spring-mvc', 'spring-data-rest']",502,TRUE,1,1
How to properly test spring boot applications?,"<p>This is kind of architectural and a broad question. </p>

<p>I have a spring rest app with three layers. (1) Front controllers (rest or mvc controllers), (2) a service layer between controllers and DAO, (3) a DAO layer which is spring data jpa repositories in my case. Now, the question is, I have written integration test for the controllers using @WebMvcTest with test slicing. For the DAO layer, I am using @DataJpaTest which is sliced testing for JPA repositories. The service layer is plain java classes so I have just unit tests with mocked DAO's.</p>

<ol>
<li><p>Now, is there still a good reason for doing a full integration testing which will start the whole container and hit up to the DB?</p></li>
<li><p>I also send SpringApplicationEvents inside my application. Is there any need to test if they are working properly? And if yes, how?</p></li>
<li><p>The service layer also controls transactions. Again, is there a need to test if transactions working as expected, and how?</p></li>
</ol>

<p>Thanks in advance        </p>
",https://stackoverflow.com/questions/45127139/how-to-properly-test-spring-boot-applications,"['spring', 'unit-testing', 'spring-mvc', 'spring-boot', 'integration-testing']",379,TRUE,1,1
unable to use localdb and dacpac for integration tests on ci server,"<p>I have large project that uses SSDT DACPACs for database changes and migrations.
I am attempting to implement integration testing by deploying the entire schema to a localdb and running tests against this db. </p>

<p>I use the below powershell script to deploy the dac and the build server outputs reports the following:</p>

<pre><code>LocalDB instance ""MSSQLLocalDB"" created with version 13.0.2151.0.
LocalDB instance ""MSSQLLocalDB"" started.
Name:               MSSQLLocalDB
Version:            13.0.2151.0
Shared name:        
Owner:              NT AUTHORITY\SYSTEM
...
Creating [tr_MStran_alterview]...
Update complete.
Updating database (Complete)
</code></pre>

<p>The database appears to be deployed. However the unit tests cannot connect to the database and I cannot see them in VS SQL Server Object Explorer (open as system account). </p>

<p>I believe it is configured correctly. I have the dacpac publish profile configured to target the following connection string <code>&lt;TargetConnectionString&gt;Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False&lt;/TargetConnectionString&gt;</code>: <code>&lt;TargetDatabaseName&gt;somedatabase_integrationTest&lt;/TargetDatabaseName&gt;</code></p>

<p>I tested it on my local machine and it worked but I need it to work on the build server.
My test project is configured to connect to the following db:
<code>&lt;add name=""ConnectionString"" connectionString=""Server=(localdb)\MSSQLLocalDB;Database=somedatabase_integrationtest;Integrated Security=True;Connection Timeout=300""/&gt;</code></p>

<p>All tasks are performed using bamboo which runs under the system account. </p>

<pre><code>function setupLocalDB() {
    sqllocaldb info 
    sqllocaldb create mssqllocaldb
    sqllocaldb start mssqllocaldb 
    sqllocaldb info mssqllocaldb
    $env:UserDomain
    $env:ComputerName
}
function publishDacFile($dacProfilePath, $dacPacFilePath) {
    #load DLL
    $dacLibPath = join-path $pwd Microsoft.SqlServer.DacFx.x86.140.3652.3\lib\net40\Microsoft.SqlServer.Dac.dll
    Add-Type -path $dacLibPath
    #load Profile
    $dacProfile = [Microsoft.SqlServer.Dac.DacProfile]::Load($dacProfilePath)
    $dacService = new-object Microsoft.SqlServer.Dac.DacServices($dacProfile.TargetConnectionString)

    Register-ObjectEvent -InputObject $dacService -EventName ""Message"" -Action { Write-Host $EventArgs.Message.Message } | out-null

    $dacPublishOptions = new-object Microsoft.SqlServer.Dac.PublishOptions
    $dacPublishOptions.DeployOptions = $dacProfile.DeployOptions
    $dacPublishOptions.GenerateDeploymentReport = $true
    $dacPublishOptions.GenerateDeploymentScript = $false
    # Load dacpac from file &amp; deploy to database named publish

    $dacPac = [Microsoft.SqlServer.Dac.DacPackage]::Load($dacPacFilePath) 
    $publishResult = $dacService.Publish($dacPac, $dacProfile.TargetDatabaseName, $dacPublishOptions)
    $publishResult.DeploymentReport
}
</code></pre>

<p>How can I get the tests to see the localdb instance without messing around with user accounts or installing full blown SQL Server?</p>
",https://stackoverflow.com/questions/43906946/unable-to-use-localdb-and-dacpac-for-integration-tests-on-ci-server,"['sql-server', 'powershell', 'continuous-integration', 'sql-server-data-tools']",556,FALSE,0,0
Using Appium and Espresso together a bad idea?,"<p>I'm a fanboy of Test-pyramid application in software development and want the same to be applied in Mobile software development as well.</p>

<p>For this, I'm desiring to leverage both Appium (for functional tests) and Espresso (for Integration Tests), and have the following questions:
The structure of my tests in Android Studio with Gradle has only 2 folders: <code>app/src/test</code> and <code>app/src/androidTest</code>.
The former test is meant for writing Unit tests with JUnit. The later for functional tests; and I'm using espresso tests for integration-testing making use of the latter directory.</p>

<p>I know I can create a separate project for Appium and write functional tests. But prefer to have those as part of the project in separate test source directory, so that it can be run at different intervals in my CI pipeline. How do I go about doing this? Is it possible to create another source test directory like <code>app/src/functionalTest</code>? Pointers to sample projects in github or resources is well appreciated.</p>
",https://stackoverflow.com/questions/41794648/using-appium-and-espresso-together-a-bad-idea,"['android', 'appium', 'android-espresso', 'functional-testing', 'test-pyramid']",217,FALSE,0,0
Generate bearer token client side C#,"<p>Im am working with a REST service deployed in an azure environment. I want to run some integration testing by calling various API functions from a separate (console) application. But the REST api uses bearer token authentication. Im a total noob with azure authentications, so i don't even know if it should be possible.</p>
<p>I've tried to use the example found <a href=""https://stackoverflow.com/questions/39407952/adal-net-core-nuget-package-does-not-support-userpasswordcredential"">here</a> but no luck yet.</p>
<p>In anycase, I have two applications. One is the console app that is running the code, and the other is the Rest service for which i need to use the bearer token to access the API calls. I will call them the ConsoleApp and RestService.</p>
<p>The code I run is as following:</p>
<pre><code>HttpClient client = new HttpClient();
string tenantId = &quot;&lt;Azure tenant id&gt;&quot;;
string tokenEndpoint = $&quot;https://login.microsoftonline.com/{tenantId}/oauth2/token&quot;;
string resourceUrl = &quot;&lt;RestService app id url&gt;&quot;;
string clientId = &quot;&lt;azure id of the ConsoleApp&gt;&quot;;
string userName = &quot;derp@flerp.onmicrosoft.com&quot;;
string password = &quot;somepassword&quot;;

string tokenEndpoint = $&quot;https://login.microsoftonline.com/{tenantId}/oauth2/token&quot;;
var body = $&quot;resource={resourceUrl}&amp;client_id={clientId}&amp;grant_type=password&amp;username={userName}&amp;password={password}&quot;;
var stringContent = new StringContent(body, Encoding.UTF8, &quot;application/x-www-form-urlencoded&quot;);

var result=await client.PostAsync(tokenEndpoint, stringContent).ContinueWith&lt;string&gt;((response) =&gt;
{
    return response.Result.Content.ReadAsStringAsync().Result;
});
</code></pre>
<p>JObject jobject = JObject.Parse(result);</p>
<p>The Json message I get back:</p>
<blockquote>
<p>error: invalid_grant, error_description: AADSTS50105: The signed in
user is not assigned to a role for the application &quot;RestService
azureid&quot;</p>
</blockquote>
<p>What does that mean, and how what needs to be done to get a bearer token out of this?</p>
",https://stackoverflow.com/questions/43854229/generate-bearer-token-client-side-c,"['c#', 'rest', 'oauth', 'azure-active-directory']",676,TRUE,0,1
Maven Testing - How can I get current Maven Settings from Java,"<p>I'm building integration testing for a WCC-Component in Maven.  </p>

<p>In mavens <code>pom.xml</code> I have a plugin configured too:</p>

<ol>
<li>Build the component</li>
<li>deploy the component</li>
<li>enable the component</li>
<li>restart the component</li>
</ol>

<p>Once that is complete I'm working on Getting the <strong>Maven-Failsafe-Plugin</strong> to test the installed plugin.</p>

<p>Before I can test the plugin I need to set some things up.  I decided the easiest way would be to create a parent class for my Integration tests that would only initialize if it hadn't been run already.</p>

<p>Example:</p>

<pre><code>@BeforeClass
public static initialize()
{  
   //lazy init here
}
</code></pre>

<p>since my component is already installed/enabled from the maven configuration I want to leverage that information instead of duplicating it for the integration tests.</p>

<p>In my <code>pom.xml</code> I have:</p>

<pre><code>&lt;plugin&gt;
  &lt;groupId&gt;org.ucmtwine&lt;/groupId&gt;
  &lt;artifactId&gt;ucm-maven-plugin&lt;/artifactId&gt;
  &lt;version&gt;0.1.2-SNAPSHOT&lt;/version&gt;
  &lt;extensions&gt;true&lt;/extensions&gt; &lt;!-- Allows WCC packaging type --&gt;
  &lt;configuration&gt;
    &lt;servers&gt;
      &lt;server&gt;            
        &lt;id&gt;sandbox&lt;/id&gt;
        &lt;url&gt;http://localhost:16200/cs/idcplg&lt;/url&gt;
        &lt;username&gt;myUser&lt;/username&gt;
        &lt;password&gt;myPass&lt;/password&gt;
        &lt;adminServer&gt;
          &lt;hostname&gt;localhost&lt;/hostname&gt; 
          &lt;serverName&gt;AdminAServer&lt;/serverName&gt; 
          &lt;wlsServerName&gt;UCM_server1&lt;/wlsServerName&gt; 
        &lt;/adminServer&gt;
      &lt;/server&gt;
    &lt;/servers&gt;
  &lt;/configuration&gt;
&lt;/plugin&gt;
</code></pre>

<p>How can I access that information from my <code>@BeforeClass</code> initialization method?  Additionally my Maven plugin also supports <code>-Dserver</code> so the user can choose which server configuration to use (based on ID).  How would I access that parameter as well?</p>

<p><strong>Note:</strong> I am not using <code>settings.xml</code> for this.</p>
",https://stackoverflow.com/questions/45490372/maven-testing-how-can-i-get-current-maven-settings-from-java,"['java', 'maven', 'maven-failsafe-plugin', 'oracle-ucm']",87,TRUE,0,1
How to make spring-boot application access different configurations for database for different scopes?,"<p>This used to be the previous scenario.</p>

<pre><code>@Bean
  @ConfigurationProperties(""database"")
  public DataSource database1DataSource() {
    return DataSourceBuilder.create().build();
  }
</code></pre>

<p>Now, to test SQL queries, I added this,</p>

<pre><code>@Bean
  @ConfigurationProperties(""testdatabase"")
  public DataSource myperksTestDataSource() { 
    return  DataSourceBuilder.create().build();
  }
</code></pre>

<p>Similarly, I have created 2 methods each for <code>PlatformTransactionManager</code> and <code>SqlSessionFactory</code>. I realised that Spring-boot picks up <code>SqlSessionFactory</code> and if I create two there will be a conflict and there will be an <code>IllegalStateException</code> with Failed to load application context.</p>

<hr>

<p><strong>Situation</strong>:</p>

<p>I want to create two databases connection, one for production and another for integration testing. I have created configurations for each in <code>application.yml</code> file. I want spring to pick up appropriate configurations.</p>

<hr>

<p><strong>What I tried</strong></p>

<p>I annotated production beans with <code>@Primary</code>. Which worked. I could get spring to run.</p>

<hr>

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

<p>I do not use <code>SqlSessionFactory</code> directly, Spring does. If I mark <code>SqlSessionFactory</code> with primary and write another, it is of no use since no method is going to call it.</p>

<p>So, as a means of solution, I thought of conditionally assigning <code>SqlSessionFactory</code> with different datasources. But, how would I identify that the run time is a test.</p>
",https://stackoverflow.com/questions/43603715/how-to-make-spring-boot-application-access-different-configurations-for-database,"['java', 'spring', 'spring-boot']",396,TRUE,0,2
Unhandled Exception in Background Worker,"<p>Hi there I am carrying out some integration testing in an application I am developing.  The specific element that is causing an issue is a call to a  background worker which interrogates an Oracle database.  When an error is encountered in the query I want the exception detail to percolate up the call stack to the application level and at that point provide an appropriate user compatible message.  In the example test there is a syntax error in the underlying SQL which results in an OraEx Exception:</p>

<pre><code>Oracle.DataAccess.Client.OracleException ORA-00907: missing right parenthesis
</code></pre>

<p>Unfortunately the code generates the following exception:</p>

<pre><code>System.Reflection.TargetInvocationException was unhandled
Message: An unhandled exception of type
'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an
invocation.
</code></pre>

<p>in the DoWork sub of the backgroundworker, despite my belief that I am handling the exception correctly.  Its pretty obvious that I am missing something fundamental here, can someone suggest a solution please.</p>

<p>Thanks in Advance
Paul J.</p>

<p>Here is the code that makes the call to the background worker:</p>

<pre><code>Private Sub EventSearch(ByVal mySQL As String)

    Const procName As String = ""EventSearch""

    Try
        _eventMngr = New ScadaEventManager(_CurrentDB, _userName, _myPwd)
        _eventMngr.SQL = mySQL

        'Set the flag and stop query tool status accordingly
        _Stopped = False
        uxStopQueryTool.Enabled = True

        'activate the timer object to ensure that the execute query menu 
        'and tool remain disabled until all background processing is complete
        uxBackWorkTimer.Enabled = True

        _logger.SendLog(Me.Name &amp; ""."" &amp; procName &amp; "" - Scanning for data."", NLog.LogLevel.Trace)
        ReviseStatus(2, ""Scanning for data.  Please wait..."", Color.Black, True, True)

        'Force the thread to sleep for half a second so the user can see the scanning state taking place
        Threading.Thread.Sleep(500)

        'Launch the background worker to retrieve the required data from the database
        uxBWScan.RunWorkerAsync(_eventMngr)

    Catch ex As Exception

        MsgBox(ex.Message, MsgBoxStyle.Exclamation, My.Application.Info.ProductName)
        _logger.SendLog(ex.Message &amp; "".  Thrown in module "" &amp; Me.Name.ToString &amp; ""."" &amp; procName, NLog.LogLevel.Error, ex)
        Call ResetStatus()

    Finally

    End Try

End Sub
</code></pre>

<p>And here is the code executed by the background worker:</p>

<pre><code>Private Sub uxBWScan_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles uxBWScan.DoWork
    Const procName As String = ""uxBWScan_DoWork""
    Try
        e.Argument.CountRecords(_queryTypeID)
        e.Result = e.Argument.RecordCount
    Catch NullEx As NullReferenceException
        _logger.SendLog(NullEx.Message &amp; "".  Thrown in module "" &amp; Me.Name.ToString &amp; ""."" &amp; procName, NLog.LogLevel.Error, NullEx)
        Throw
    Catch OraEx As OracleException
        _logger.SendLog(OraEx.Message &amp; "".  Thrown in module "" &amp; Me.Name.ToString &amp; ""."" &amp; procName, NLog.LogLevel.Error, OraEx)
        Throw
    Finally
    End Try
End Sub
</code></pre>

<p>And here is the low level code that generates the error:</p>

<pre><code>    Public Sub CountRecords(ByVal queryType As Integer)

        _myDataset = New DataSet
        Try
            _myDataset = _myScadaEventDB.CountRecords(_sqlText)
            If _myDataset.Tables(0).Rows.Count &gt; 0 Then
                If queryType = Enums.QueryType.General Or queryType = Enums.QueryType.KeyPerformanceIndicators Or queryType = Enums.QueryType.TelecontroAnalysis Then
                    _recordCount = _myDataset.Tables(0).Rows(0).Item(""RecordCount"")
                Else
                    'The query is grouped therefore count the number of records in the table 
                    _recordCount = _myDataset.Tables(0).Rows.Count
                End If
            Else
                _recordCount = 0
            End If
        Catch ex As Exception
            Throw
        Finally

        End Try

    End Sub
</code></pre>
",https://stackoverflow.com/questions/42815647/unhandled-exception-in-background-worker,"['vb.net', 'oracle11g', 'exception', 'backgroundworker']",649,FALSE,0,1
Unable to set runtime Local Server Port in Spring Boot Test 1.5,"<p>I am using Spring Boot 1.5 for my application. In integration testing I want to fetch the runtime port number of the web server(note: TestRestTemplate is not useful in my case.). There are a few approaches I have tried but none of them seem to work. Below are my approaches.</p>

<p><strong>First Approach</strong></p>

<pre><code>@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT)
public class RestServiceTest {

@LocalServerPort      
protected int port;
</code></pre>

<p>In my <code>src/main/resources/config/application.properties</code> file I have defined server port as</p>

<blockquote>
  <p>server.port = 8081</p>
</blockquote>

<p>But With this code I am getting error</p>

<blockquote>
  <p>Could not resolve placeholder 'local.server.port' in value ""${local.server.port}""</p>
</blockquote>

<p><strong>Second Approach</strong></p>

<p>I have changed</p>

<blockquote>
  <p>webEnvironment =WebEnvironment.DEFINED_PORT</p>
</blockquote>

<p>to</p>

<blockquote>
  <p>webEnvironment =WebEnvironment.RANDOM_PORT</p>
</blockquote>

<p>and in my <code>src/main/resources/config/application.properties</code> file I have defined </p>

<blockquote>
  <p>server.port = 0</p>
</blockquote>

<p>This throws the same as error as the first approach.</p>

<p><strong>Third Approach</strong></p>

<p>In third approach I have tried to use </p>

<pre><code>protected int port;

@Autowired
Environment environment

this.port = this.environment.getProperty(""local.server.port"");
</code></pre>

<p>this returns <code>null</code> value</p>

<p><strong>Fourth Approach</strong></p>

<p>Lastly I have tried to use <code>ApplicationEvents</code> to find out the port number by creating an event listener to listen to <code>EmbeddedServletContainerIntialize</code></p>

<pre><code>@EventListener(EmbeddedServletContainerInitializedEvent.class)
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
this.port = event.getEmbeddedServletContainer().getPort();
}

public int getPort() {
return this.port;
} 
</code></pre>

<p>Added the same to <code>TestConfig</code></p>

<p>Now, In my test class I have tried use this listener to get the port</p>

<pre><code>@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.RANDOM_PORT)
public class RestServiceTest {

protected int port;

@Autowired
EmbeddedServletContainerIntializedEventListener embeddedServletcontainerPort;

this.port = this.embeddedServletcontainerPort.getPort();
</code></pre>

<p>this returns <code>0</code>. Also, I have found out listener event is never triggered.</p>

<p>It is very straight forward as in the docs and other posts but somehow It is not working for me. Help is much appreciated.</p>
",https://stackoverflow.com/questions/43491893/unable-to-set-runtime-local-server-port-in-spring-boot-test-1-5,"['java', 'spring', 'testing', 'spring-boot', 'webserver']",21336,TRUE,15,4
ASPNet.Core HostingEnvironment for Integration Tests?,"<p>In building the Integration tests for my ASPNet.Core web app, <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing</a>,
I am coming across an issue. The Startup is run when I run the app and the configuration is read and contains all the information in my <code>apsettings.json</code> file.
Now, when I run the integration test as shown below. the Startup is run but the configuration is different. Why would that happen and how do I make sure it reads 
the one for the app itself?</p>

<pre><code>[TestFixture]
class HSMControllerTests
{
    private readonly TestServer _server;
    private readonly HttpClient _client;

    public HSMControllerTests()
    {
        _server = new TestServer(new WebHostBuilder()
        .UseStartup&lt;Startup&gt;());
        _client = _server.CreateClient();
    }

    [Test]
    public async global::System.Threading.Tasks.Task GET_PingHSM_ShouldSucceedAsync()
    {
        HttpResponseMessage response = await _client.GetAsync(""HSM/PingHSM"");
        Assert.NotNull(response);
        Assert.IsInstanceOf&lt;OkObjectResult&gt;(response);
    }
}
</code></pre>

<p>I am getting the exception <code>Missing configuration section ServiceConfig.</code></p>

<p>This is how the WebHost is built in <code>Program.cs</code> in my app:</p>

<pre><code>WebHost.CreateDefaultBuilder(args)
       .UseStartup&lt;Startup&gt;()
       .UseKestrel(o =&gt; o.AddServerHeader = false)
       .Build();
</code></pre>

<p>Could the difference in how it is built in the Test code be the problem?</p>

<p><strong>Modified ControllerTest constructor:</strong></p>

<pre><code>public HSMControllerTests()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Path.GetFullPath(@""../../../../HSM.WebApi.IntegrationTests""))
        .AddJsonFile(""appsettings.json"", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();

    _server = new TestServer(WebHost.CreateDefaultBuilder()
        .UseStartup&lt;Startup&gt;());
    _client = _server.CreateClient();
}
</code></pre>

<p>Now, how to inject the new Configuration into the Startup? Our Startup is defined like this:</p>

<pre><code>public Startup(IConfiguration configuration, IHostingEnvironment environment)
        : base(typeof(Startup), configuration, environment)
{
}
</code></pre>

<p><strong>modification based on last post by @poke</strong></p>

<pre><code>_server = new TestServer(WebHost.CreateDefaultBuilder()
    .ConfigureAppConfiguration(configBuilder =&gt; new ConfigurationBuilder()
        .SetBasePath(Path.GetFullPath(@""../../../../HSM.WebApi.IntegrationTests""))
        .AddJsonFile(""appsettings.json"", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables()
    )
    .UseStartup&lt;Startup&gt;());
</code></pre>

<p><strong>Got it working, somewhat...</strong></p>

<pre><code>var config = new ConfigurationBuilder()
    .SetBasePath(Path.GetFullPath(@""../../../../HSM.WebApi.IntegrationTests""))
    .AddJsonFile(""appsettings.json"", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables();

var Configuration = config.Build();

_server = new TestServer(WebHost.CreateDefaultBuilder()
    .UseConfiguration(Configuration)
    .UseStartup&lt;Startup&gt;());
_client = _server.CreateClient();
</code></pre>

<p>But now, the HostingEnvironment is set to the directory of the Tests app vs. the directory of the Web app and it attempts to read to <code>appsettings.json</code> file from there in the HomeController constructor, here:</p>

<pre><code>public HSMController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
    contentRootPath = _hostingEnvironment.ContentRootPath;
}
</code></pre>
",https://stackoverflow.com/questions/46978553/aspnet-core-hostingenvironment-for-integration-tests,"['c#', 'unit-testing', 'asp.net-core', 'asp.net-core-mvc-2.0']",5374,TRUE,6,2
PayPal Express Checkout with debit card throws error in sandbox environment,"<p>I just integrated the <a href=""https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/basic-integration/"" rel=""nofollow noreferrer"">PayPal Express Checkout</a> for my shopping cart with basic client integration. I used the sandbox environment for integration testing and everything works well if the sandbox test account (""PERSONAL"") of the sandbox environment has either a positive PayPal balance or a credit card deposited to the sandbox test account. </p>

<p>But if the sandbox test account has only a debit card deposited, then it is not possible to charge the PayPal account, I receive following error due to <code>actions.payment.execute()</code> in the <code>onAuthorize</code> callback:</p>

<p><code>POST https://www.sandbox.paypal.com/.../createpayment - 400 Bad Request</code>
with JSON response field <em>contingency</em> set to <code>PAYMENT_NOT_APPROVED_FOR_EXECUTION</code>.</p>

<p>I am using exactly the same JavaScript code for my application as in the <a href=""https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/basic-integration/"" rel=""nofollow noreferrer"">basic client integration</a> example provided by PayPal, I just changed the 'env' to sandbox and edited my sandbox API key. I am wondering why this error is thrown when using debit card as payment method since I know from private use of PayPal that it is possible to pay with PayPal deposited debit card directly. Or is this just a sandbox specific error?</p>
",https://stackoverflow.com/questions/41637034/paypal-express-checkout-with-debit-card-throws-error-in-sandbox-environment,"['paypal', 'express-checkout']",248,FALSE,1,0
Connection string for code first mode with mysql,"<p>I am working on a project that gets connection strings for Entity Framework from environment variables, like this:</p>

<pre><code>public class SomeTests {
    [Fact]
    public async void TestSomething() {
        string connectionString = Environment.GetEnvironmentVariable(""APP_CONN_STR"");
        var appContextOptionsBuilder = new DbContextOptionsBuilder&lt;AppDataContext&gt;();
        appContextOptionsBuilder.UseMySql(connectionString); // hardcoded mysql

        AppDataContext context = new AppDataContext(appContextOptionsBuilder.Options);

        Assert.Equal(context.Country.Count(), 0);
    }
}
....

public partial class AppDataContext : DbContext, IAppDataContext
{
    public AppDataContext(DbContextOptions options) : base(options)
    {
    }

    public virtual DbSet&lt;Country&gt; Country { get; set; }

    ...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Country&gt;(entity =&gt;
        {
            entity.ToTable(""country"");
            ...
        });
        ...
    }
}
</code></pre>

<p>The code above is a bootstrapper code for some automated integration testing. Historically every developer is using the same old database instance on the network without a problem. I am trying to make these tests run in an isolated environment, so I have set up an empty new mysql database (using docker to make it reproducible), and let Entity Framework to populate it with a schema.</p>

<p>The problem is, when I create an empty database in this mysql instance and give a connection string to that database, then I am getting table not found errors:</p>

<pre><code>connection str: Server=127.0.0.1;Port=3306;Database=app_mysql_db;Uid=root;Pwd=****;

error: MySql.Data.MySqlClient.MySqlException : Table 'app_mysql_db.country' doesn't exist
</code></pre>

<p>I found out that EF will not create tables in existing databases, it will only populate a database with tables if EF itself created it. This is the default behavior of EF.</p>

<p>So I tried to remove the database name from the connection string:</p>

<pre><code>connection str: Server=127.0.0.1;Port=3306;Uid=root;Pwd=****;

error: MySql.Data.MySqlClient.MySqlException : No database selected
</code></pre>

<p>So how do I let Entity Framework in Code First mode to create my tables?</p>
",https://stackoverflow.com/questions/46813312/connection-string-for-code-first-mode-with-mysql,['entity-framework'],132,FALSE,1,0
Vuejs Unit Test - Backing Mocks with Tests,"<p>I am writing unit testing for a vuejs 2 application that uses Vuex as a store. I have the following pattern in many of my components:</p>

<p>example component thing.vue:</p>

<pre><code>&lt;template&gt;
    &lt;div&gt;
        {{ thing.label }}
    &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
  export default {
    name: 'thing',
    data() { return { } },
    computed: {
       thing () {
         return this.$store.state.thing;
       }
    }
  }

&lt;/script&gt;
</code></pre>

<p>Example Store State:</p>

<pre><code>export const state = {
    thing: { label: 'test' }
};
</code></pre>

<p>Example Unit for Thing.vue:</p>

<pre><code>describe('thing ', () =&gt; {

  const storeMock = new Vuex.Store( state: { thing: { label: 'test' } } );

  it('should pull thing from store', () =&gt; {
      const Constructor = Vue.extend(thing);
      const component new Constructor({ store }).$mount();

      expect(component.thing).toEqual({ label: 'test' });
  });

});
</code></pre>

<p>Example Unit test for Store:</p>

<pre><code>import store from './store';

describe('Vuex store ', () =&gt; {

  it('should have a thing object', () =&gt; {
      expect(store.state.thing).toEqual({ label: 'test' });
  });

});
</code></pre>

<p>There is a huge problem with this pattern.  When another developer refractors the store state, they will see the Store test fail, but because the thing unit test is based on a mocked version of the store that test with continue to pass, even though that component will never work. There isn't a good way to know a refactor invalidated a Mock.</p>

<p>So how do people unit test this type of dependence?</p>

<p>One way would be to cheat a little on the unit test and use the real store state, but then it isn't really a unit test.  The other way is rely on integration testing to catch the mock - store mismatch, but that feels like it would be painful to debug why the unit tests pass but the integration tests are failing.</p>
",https://stackoverflow.com/questions/43682881/vuejs-unit-test-backing-mocks-with-tests,"['laravel', 'unit-testing', 'jasmine', 'vue.js', 'vuex']",377,FALSE,1,1
Automated Weblogic Service Testing using Jenkins,"<p>What I am looking for is a ""best practices"" description or example by which testing can be automated for components that are deployed to a Weblogic server.</p>

<p>I am not expecting anyone to present a step by step solution to this problem.
I am looking for a <strong>resource</strong> (book, manual, website, etc.) that can describe a path to this integration and testing goal.</p>

<p>The situation is that we have a pair of (<em>Maven</em>) Project deployments (<em>in Eclipse</em>) which are managed/reviewed/maintained through: <strong>Git, Stash, and Jenkins</strong>.</p>

<p>The first component is providing Web Services (<em>RESTful</em> services as well as <em>Stateful</em> and <em>Stateless</em> services). It is connected to the second component. The second component exposes <em>Stateless</em> and <em>RESTful</em> services that provide access services (CRUD: Create Read Update Delete) to an <strong>Oracle SQL Database</strong>.</p>

<p>Currently, the <strong>Jenkins</strong> Service is testing the Client UI through <strong>Jasmine</strong> Zzzzz.spec.js tests. This is all well and good for the ""front-end hipsters"", but not helpful for the <strong>Java</strong> service component developers.</p>

<p>What I would like to do is to be able to write (?<strong>JUnit</strong>?) tests to evaluate Service component operations that can be automatically executed by <strong>Jenkins</strong> continuous integration components. What I would like to avoid doing is mocking up everything to the point that the tests become trivial and pointless.</p>

<p>What needs to happen is: <p>
1. Developer completes a Work Product (<strong>JIRA</strong> Task) to add functionality to a Service hosted by a <strong>Weblogic Server</strong>.<p>
2. Work Product contains a Test (?<strong>JUnit</strong>?). <p>
3. Work Product (including test) is pushed by <strong>Git</strong> to <strong>Stash</strong>.<p>
4. Work Product Test is added to Integration Tests. <p>
5. <strong>Stash</strong> and <strong>Jenkins</strong> execute and evaluate Work Product <strong>JUnit</strong> Test as part of [<strong>Integration Testing</strong>].<p>
<strong>Integration Testing</strong> will: <p>
 1. Start a (configured) <strong>Weblogic</strong> Server (if one is not already started). <p>
 2. Compile and Publish Deployment containing Work Product. <p>
 3. Deployment will connect to a Configured <strong>Datasource</strong>. <p>
 4. Start [<strong>Work Product JUnit Test</strong>]. <p></p>

<p><strong>Work Product JUnit Test</strong> will: <p>
1. Connect and authenticate to <strong>Weblogic</strong> Service Deployment.<p>
2. Call tested Service methods.<p>
3. Evaluate test results<p>
 <p>
Yes, that is a tall order with a hive full of buzzwords. However, I am having difficulty finding a worthwhile resource that isn't trying to direct me to mock up the very components that I am trying to test.<p></p>
",https://stackoverflow.com/questions/43212879/automated-weblogic-service-testing-using-jenkins,"['java', 'maven', 'jenkins', 'junit', 'weblogic']",319,TRUE,1,1
Unit testing and mocking a legacy wrapper that calls another service,"<p>I will gladly remove this question should duplicates be provided. Lack of knowledge in this area makes finding solutions a little more difficult.</p>

<hr>

<p>We're beginning to implement unit &amp; integration testing throughout the organisation; starting with new projects. </p>

<p>Testing code we fully own seems pretty straight forward and there are many resources we can utilize. </p>

<p>Testing code that calls out to a third-party service on the other hand is a little more difficult. I understand that mocking is what we should be looking to do, though am a little hard pressed to figure out the actual implementation for a particular piece of code. </p>

<p>In this particular case we have a new library that will be sitting between business layers &amp; a third-party exception logger (Sentry) - so it's a legacy wrapper.</p>

<p>By way of an example, the following code is a slimmed down extract.</p>

<p><strong>Interface</strong></p>

<pre><code>public interface IExceptionLogging
{
    void Capture(string endpointKey, string message, params KeyValuePair&lt;string, string&gt;[] tag);
    void Capture(string endpointKey, Exception exception, params KeyValuePair&lt;string, string&gt;[] tag);
}
</code></pre>

<p><strong>Abstract, helps to enforce constructor</strong></p>

<pre><code>public abstract class ExceptionLogging : IExceptionLogging
    {
        internal Dictionary&lt;string, Uri&gt; LoggerEndpoints;

        protected ExceptionLogging(Dictionary&lt;string, Uri&gt; loggerEndpoints)
        {
            LoggerEndpoints = loggerEndpoints;
        }

        public abstract void Capture(string endpointKey, string message, params KeyValuePair&lt;string, string&gt;[] tag);
        public abstract void Capture(string endpointKey, Exception exception, params KeyValuePair&lt;string, string&gt;[] tag);

    }
</code></pre>

<p><strong>An implementation</strong></p>

<pre><code>public class GetSentry : ExceptionLogging
{
    private Dictionary&lt;string, RavenClient&gt; _clients = new Dictionary&lt;string, RavenClient&gt;();

    public GetSentry(Dictionary&lt;string, Uri&gt; loggerEndpoints)
        : base(loggerEndpoints)
    {
        LoggerEndpoints.ToList().ForEach(ep =&gt;
        {
            _clients.Add(ep.Key, new RavenClient(ep.Value.ToString()));
        });
    }

    public override void Capture(string endpointKey, Exception ex, params KeyValuePair&lt;string, string&gt;[] tag)
    {
        RavenClient client = _clients[endpointKey];
        if (client != null)
        {
            SentryEvent se = new SentryEvent(ex);
            tag.ToList().ForEach(t =&gt; se.Tags.Add(t));
            client.Capture(se);

        }
    }    

    public override void Capture(string endpointKey, string message, params KeyValuePair&lt;string, string&gt;[] tag)
    {
        RavenClient client = _clients[endpointKey];
        if (client != null)
        {
            SentryEvent se = new SentryEvent(message);
            tag.ToList().ForEach(t =&gt; se.Tags.Add(t));
            client.Capture(se);
        }
    }
</code></pre>

<p>What would be the approach to test something like this?</p>

<p>As mentioned, I will happily remove this Q if there are valid duplicates. I am just unsure where to start.</p>
",https://stackoverflow.com/questions/43981975/unit-testing-and-mocking-a-legacy-wrapper-that-calls-another-service,"['c#', 'unit-testing', 'mocking']",147,FALSE,0,0
Can I use Cucumber to test an application that uses more than one language?,"<p>I'm currently part of a team working on a Hadoop application, parts of which will use Spark, and parts of which will use Java or Python (for instance, we can't use Sqoop or any other ingest tools included with Hadoop and will be implementing our own version of this). I'm just a data scientist so I'm really only familiar with the Spark portion, so apologies for the lack of detail or if this question just sucks in general - I just know that the engineering team needs both Java and Python support. I have been asked to look into using Cucumber (or any other BDD framework) for acceptance testing our app front to back once we're further along. I can't find any blogs, codebases, or other references where cucumber is being used in a polyglot app, and barely any where Hadoop is being used. Would it be possible to test our app using Cucumber or any other existing BDD framework? We already plan to do unit and integration testing via JUnit/PyUnit/etc as well. </p>
",https://stackoverflow.com/questions/42909952/can-i-use-cucumber-to-test-an-application-that-uses-more-than-one-language,"['java', 'python', 'hadoop', 'cucumber', 'cucumber-jvm']",1122,FALSE,0,3
How to configure Spring Boot Application to run on a specific database when launching,"<p>I have a Spring MVC Application developed with Spring Boot. This is application is just for learning purposes, by the way.</p>

<p>By default, the app launches and uses a MySQL database. For unit and integration testing, I use an in-memory H2 database and it works perfectly.</p>

<p>So for that, I have two application.properties. One is under <strong><em>/src/main/resources/application.properties</em></strong>.</p>

<pre><code>spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost/myDatabase
spring.datasource.username = root
spring.datasource.password = mysql

spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
</code></pre>

<p>The other application.properties in under <strong><em>/src/test/resources/application.properties</em></strong></p>

<pre><code>spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE""
spring.datasource.username=sa
spring.datasource.password=sa
</code></pre>

<p>Now, I have to use Selenium for automated website testing and I don't want my MySQL database to be populated with test data.</p>

<p>I haven't done this previously in Spring, but I would like my application to work like this:</p>

<ul>
<li>Launch from terminal my application with certain commands specifying what database it should use. It should launch on localhost:8080</li>
<li>And then, run all Selenium test in localhost:8080. All the data generated with Selenium tests is only kept in memory as long as the application is running</li>
</ul>

<p>How to do this in a Spring Boot Application using an application.properties or other configuration?</p>
",https://stackoverflow.com/questions/46313926/how-to-configure-spring-boot-application-to-run-on-a-specific-database-when-laun,"['spring', 'selenium', 'spring-mvc', 'spring-boot', 'application.properties']",894,TRUE,0,2
Where to write tests for a Frontend/Backend application?,"<p>I want to write a web application with a simple Frontend-Backend(REST API) architecture.
It's not clear to me where and how to write tests.</p>

<p>Frontend:  should I write tests mocking API responses and testing only UX/UI?
Backend: should I write here API call testing and eventually more fine grained unit testing on classes?</p>

<p>But in this way I'm afraid that Frontend testing is not aware of real API response (because it's mocking independently from the backend).
On the other side if I don't mock API response and use real response from backend, how can the Frontend client prepare the DB to get the data he wants?</p>

<p>It seems to me that I need 3 kind of testing types:
- UX/UI testing: the Frontend is working with a set of mock responses
- API testing: the API is giving the correct answers given a set of data
- Integration testing: The Frontend is working by calling really the backend with a set of data (generated by who?).</p>

<p>There are framework or tools to make this as painless as possible?
It seems to me very complicated (if API spec changes I must rewrite a lot of tests)</p>

<p>any suggestion welcome</p>
",https://stackoverflow.com/questions/42747791/where-to-write-tests-for-a-frontend-backend-application,"['rest', 'testing', 'frontend', 'backend']",3476,TRUE,5,2
Coldbox handler testing using testbox and asyncAll enabled,"<p>tl;dr; does anyone know how to safely do asynchronous coldbox handler integration testing using testbox?</p>

<p>I'm using coldbox 3.8.1.00076 and testbox 1.1.0.00076 and have created some integration tests similar to the example below and to make them run faster enabled asyncAll for them, however it seems the BaseTestCase execute method is not thread safe and shares the request context (and controller, etc) with all the threads in the cfc so Thread A (aTest) and Thread B (bTest) can sometimes end up returning the exact same event object which will contain the rendered result of whichever thread finished last... ish.</p>

<p>They mention in the <a href=""https://testbox.ortusbooks.com/content/primers/xunit/asynchronous_testing.html"" rel=""nofollow noreferrer"">docs</a> to ensure tests are thread safe by properly scoping variables which they are and in their async example they reload wirebox but as the thread issues are coming from the shared coldbox objects i doubt this would help, i have tried it just in case but it also breaks the tests anyway as the example seems to be missing getting wirebox to configure with existing mappings but i didn't bother working out how to do that as i doubt it would solve my issue anyway.</p>

<h1>Example Test</h1>

<pre><code>component extends=""coldbox.system.testing.BaseTestCase"" asyncAll=""true""{

    public function aTest() output=""false""{
        var event = execute(event:""someHandler.a"", renderResults: true);
        var cbox_rendered_content = event.getValue(""cbox_rendered_content"", """");
        $assert.includes(cbox_rendered_content, ""SOME_UNIQUE_CONTENT_TO_A""); //fails here when b content is returned
    }

    public function bTest() output=""false""{
        var event = execute(event:""someHandler.b"", renderResults: true);
        var cbox_rendered_content = event.getValue(""cbox_rendered_content"", """");
        $assert.includes(cbox_rendered_content, ""SOME_UNIQUE_CONTENT_TO_B""); //fails here when a content is returned
    }
}
</code></pre>

<h1>Example Runner</h1>

<pre><code>&lt;!--- Executes all tests in the 'specs' folder with simple reporter by default ---&gt;
&lt;cfparam name=""url.reporter""        default=""simple""&gt;
&lt;cfparam name=""url.directory""       default=""test.specs""&gt;
&lt;cfparam name=""url.recurse""         default=""true"" type=""boolean""&gt;
&lt;cfparam name=""url.bundles""         default=""""&gt;
&lt;cfparam name=""url.labels""          default=""""&gt;
&lt;cfparam name=""url.reportpath""      default=""#expandPath( ""/test/results"" )#""&gt;
&lt;cfparam name=""url.propertiesFilename""  default=""TEST.properties""&gt;
&lt;cfparam name=""url.propertiesSummary""   default=""false"" type=""boolean""&gt;

&lt;!--- Include the TestBox HTML Runner ---&gt;
&lt;cfinclude template=""/coldbox/system/testing/runners/HTMLRunner.cfm"" &gt;
</code></pre>
",https://stackoverflow.com/questions/46361989/coldbox-handler-testing-using-testbox-and-asyncall-enabled,"['coldfusion', 'integration-testing', 'cfml', 'cfc', 'coldbox']",248,FALSE,2,0
H2 vs HSQLDB vs Derby | In-memory RDBMS for a Reporting APP,"<p>I'm designing a Data REST API for the purpose of dynamic reporting. Basically, you pass in the data to it (along with the functions to manipulate the data) and it returns you a HTML with the functions applied on the data. Typically, these functions would be filtering, grouping, aggregating, sorting (what a regular RDBMS would offer). 
I'm contemplating as to use an in-memory DB for this. By doing so, I'll simply leverage the functions offered by the DB rather than having to implement myself.</p>

<p>However, this requires the service to load the data (perhaps bulk load) and then run series of queries constructed dynamically - as part of every service call.</p>

<p>The data (input) to be loaded in the database can be max 100K rows. Certainly not millions!</p>

<p>But the service can be accessed by different threads (each will load their data-set into the database and read concurrently). Of-course the jdbc connection will be pooled and the tables will be truncated at the end of every transaction.</p>

<p>I'm asking myself that am I going overboard and trying to exploit the in-memory dbs? I have used it myself (and often hear) about in-memory dbs (especially H2 and HSQL) only in the context of integration testing.</p>

<p>Would be interested to hear your views.</p>
",https://stackoverflow.com/questions/44570714/h2-vs-hsqldb-vs-derby-in-memory-rdbms-for-a-reporting-app,"['h2', 'derby', 'hsqldb', 'in-memory-database']",5019,FALSE,6,0
Testing component in Android App SDLC?,"<p>""Automated testing is an integral part of the development lifecycle.""</p>

<p>In android app proejcts we've implemented MVP, Rx with Retrofit and Content Provider/SQLite, dagger. Every android apps will always have server communication, storing data in local database,  complex ui like naviagtion drawer and recycler view etc, and difficult navigation flow of application.</p>

<p>What we want to achieve?</p>

<ul>
<li>Few test cases which should be tested every time before we deliver the apk to client or release on play store?(20-30% automate testing)</li>
<li>List of test cases of business logic, which can not be auto tested because whatever reason like complex ui, navigation flow etc (40-60% manual testing)</li>
<li>Continuous Integration</li>
</ul>

<p>Based on above, there are few questions,</p>

<ul>
<li>What to test in auto and manual, how to decide that?</li>
<li>In automate testing, where to test in MVP - Model-View-Presenter layers?</li>
<li>What kind of general business logic should auto test for mobile apps - like registration, login, forgot password, update profile etc?</li>
<li>What type of testing should perform for android apps - unit testing, functional testing, integration testing, manual testing, performance testing, regression testing</li>
<li>Which tool to use - android testing support library, espresso, uiautomator, Robotium, roboelectric, appium, selendroid, mockito, JUnit</li>
</ul>

<p>(Feel free to improve check list as we don't know best practices for testing module in SDLC for android mobile app.) originally asked, <a href=""https://softwareengineering.stackexchange.com/questions/345061/testing-component-in-android-app-sdlc"">here</a>.</p>
",https://stackoverflow.com/questions/43066372/testing-component-in-android-app-sdlc,"['android', 'testing', 'continuous-integration', 'tdd', 'android-testing']",258,TRUE,11,1
How does initdb of PostgreSQL work? How to use it for testing?,"<p>Many suggestions for integration testing which includes Postgres Database say that I can <code>initdb</code> a new whole cluster in RAM disk and work on it.</p>

<p>As far as I understand <code>initdb</code> is a new folder like thing related to databases.</p>

<p>According to Postgres docs:</p>

<blockquote>
  <p><code>initdb</code> creates a new PostgreSQL database cluster. A database cluster is a collection of databases that are managed by a single server instance.</p>
</blockquote>

<p>Does it create a new server?  Or a new Database?</p>

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

<blockquote>
  <p>Creating a database cluster consists of creating the directories in which the database data will live, generating the shared catalogue tables (tables that belong to the whole cluster rather than to any particular database), and creating the template1 and Postgres databases. When you later create a new database, everything in the template1 database is copied. (Therefore, anything installed in template1 is automatically copied into each database created later.) The Postgres database is a default database meant for use by users, utilities and third party applications.</p>
</blockquote>

<p>Does the above sentence mean that from now on whatever database is created it is stored in that new ""cluster""? If not how to create tables in such a cluster of RAM disk?</p>

<hr>

<p>How can I use it to set it up for testing? </p>
",https://stackoverflow.com/questions/43843896/how-does-initdb-of-postgresql-work-how-to-use-it-for-testing,"['postgresql', 'integration-testing', 'ramdisk']",4122,TRUE,3,1
Define and use function pointer type referring to functions with parameters of different enum types,"<p>I have a pair of functions that both accept multiple parameters. Both function signatures are the same type except for one enum parameter:</p>

<pre><code>typedef enum { a_1, a_2, a_3 } enum_a_t;
typedef enum_a_t * enum_a_p;

typedef enum { b_1, b_2      } enum_b_t;
typedef enum_b_t * enum_b_p;

void func_a(int ai, float af, enum_a_p ae_ptr) { /* blah */ }
void func_b(int ai, float af, enum_b_p ae_ptr) { /* blah */ }
</code></pre>

<p>Now because in my head I think of enums being implemented as integers, I thought maybe I could typedef a function that is compatible with both of these signatures, something like:</p>

<pre><code>typedef void (* func_t)(int, float, int *);
</code></pre>

<p>But of course when assigning either of these functions to a variable of that type (e.g. <code>func_t f_a = func_a</code>), llvm-gcc complains:</p>

<pre><code>warning: incompatible pointer types initializing 'func_t' (aka 'void (*)(int, float, int *)') with an expression of type 'void (int, float, enum_a_p)' (aka 'void (int, float, enum_a_t *)') [-Wincompatible-pointer-types]
</code></pre>

<p>I realize it's only a warning and I can probably get away with it if I'm careful, but I was curious if there is a strict / type-safe way to do something like this in C? </p>

<p>I would like to not have a warning on assignment, and I would like to be able to treat these functions as a common type without having to change their declared parameter lists.</p>

<p><strong><em>edit</em></strong></p>

<p>This is a very small example of the problem I'm experiencing in a much larger code base. Changing the declared parameter lists would require typecasting all direct invocations of those functions elsewhere in the code - a major change that would require a <em>lot</em> of integration testing (days of testing then involving others (this is on a weird embedded platform)) in areas of the code I really don't need to be modifying.</p>
",https://stackoverflow.com/questions/45201934/define-and-use-function-pointer-type-referring-to-functions-with-parameters-of-d,"['c', 'enums', 'function-pointers', 'function-prototypes']",532,FALSE,3,2
Can you use a classpath file to configure DispatcherServlet with &lt;init-param&gt;?,"<p>I was going through the Spring configuration files in a web application I’m working at and we have this in our <code>web.xml</code>:</p>

<pre><code>&lt;context-param&gt;
    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
    &lt;param-value&gt;classpath:applicationContext.xml&lt;/param-value&gt;
&lt;/context-param&gt;

&lt;listener&gt;
    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;

&lt;servlet&gt;
    &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
</code></pre>

<p>The reason why <code>applicationContext.xml</code> is loaded from the classpath, instead of the more usual <code>/WEB-INF/applicationContext.xml</code>, is because there are certain properties such as JDBC connection details that are filtered by Maven according to the profile used to build/run the app (integration testing, functional testing, production...). This all works, but if I change it to the configuration below (removing the <code>&lt;context-param&gt;</code> and <code>&lt;listener&gt;</code> entries):</p>

<pre><code>&lt;servlet&gt;
    &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;classpath:applicationContext.xml&lt;/param-value&gt;
    &lt;/init-param&gt;
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
</code></pre>

<p>The logs say the application starts up correctly and the web application context is loaded from the XML file:</p>

<pre><code>...
11:57:15.910 [RMI TCP Connection(2)-127.0.0.1] INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization started
11:57:15.927 [RMI TCP Connection(2)-127.0.0.1] INFO  org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Aug 22 11:57:15 BST 2017]; root of context hierarchy
11:57:15.958 [RMI TCP Connection(2)-127.0.0.1] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
...
</code></pre>

<p>But when I try to get any page Tomcat replies with a 404 error and the following NPE in the logs (we’re using Tiles 3):</p>

<pre><code>SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
    at org.apache.tiles.access.TilesAccess.getContainer(TilesAccess.java:124)
    at org.apache.tiles.access.TilesAccess.getContainer(TilesAccess.java:107)
    at org.apache.tiles.access.TilesAccess.getCurrentContainer(TilesAccess.java:174)
    at org.apache.tiles.template.InsertDefinitionModel.execute(InsertDefinitionModel.java:95)
    at org.apache.tiles.jsp.taglib.InsertDefinitionTag.doTag(InsertDefinitionTag.java:254)
    at ...
</code></pre>

<p>I’ve seen in other SO questions that you can configure your servlet using <code>&lt;init-param&gt;</code> if you don’t need to share the context among servlets (usually if you’re just running a single one); however all the examples I’ve seen use an absolute path to indicate the location of <code>applicationContext.xml</code>, so I was wondering that maybe it wasn’t possible to load the WAC using the classpath at all? Have you tried to do so successfully or do you know the reason why you can’t?</p>
",https://stackoverflow.com/questions/45816048/can-you-use-a-classpath-file-to-configure-dispatcherservlet-with-init-param,"['java', 'spring', 'spring-mvc']",435,FALSE,2,0
Setting process exit code from GUI application,"<p>I'm writing a small integration testing framework to a suite of application written in Delphi 10.2 (win32 target).</p>

<p>My idea was to detect a specific command-lien parameter and, if it is present, run the test, printing the result to STDOUT and the console and then exiting with either 0 (no error) or 1 (error) so that the build script can pickup the result.</p>

<p>That worked well except for the last part: I'm unable to set the process exit code properly and read it back from the calling script. I'm always getting the value -1073741515 back instead.</p>

<p>Since the program is, in theory, a GUI application, I wrote some code that would allow it to attach to the calling console (or create one if not present) and maybe my problem comes from that.</p>

<p>Here is my code:</p>

<pre><code>  UIAbstraction.writeln('Integration testing of '+ModuleName, dmEmphasis);
  if Errors.Count &gt; 0 then
  begin
    UIAbstraction.writeln('Erros occured during integration tests:');
    Errors.ForEach(procedure (const Aline: string)
      begin
        UIAbstraction.writeln(ALine, dmError);
      end
    );
    UIAbstraction.Detach;
    ExitProcess(cardinal(1));
  end
  else
  begin
    UIAbstraction.writeln('Integration tests sucessfull', dmSuccess);
    UIAbstraction.Detach;
    ExitProcess(cardinal(0));
  end;
</code></pre>

<p>UIAbstraction is a small class that, well, abstract the UI (the goal is to be easily able to inject a different implementation later that could integrate with a different integration test system). It mostly has 2 meaningful methods: Attach and detach:</p>

<pre><code>procedure TConsoleConnector.Attach;
begin
  IsAttached:=AttachConsole(-1);
  if not IsAttached then
    IsAttached := GetlastError = 5; // 5 = ACCESS_DENIED = already attached
  if not IsAttached
  then
  begin
    IsAttached:=AllocConsole;
    if not IsAttached then
      RaiseLastOSError;
  end;
end;


procedure TConsoleConnector.Detach;
begin
  if IsAttached then
    FreeConsole;
  IsAttached:=false;
end;
</code></pre>

<p>Unfortunately, when I run this code from the command line and follows it with <code>echo %errorlevel%</code> I always get <code>-1073741515</code> instead of the expected 0 or 1.</p>
",https://stackoverflow.com/questions/46547222/setting-process-exit-code-from-gui-application,"['windows', 'delphi', 'winapi', 'delphi-10.2-tokyo']",179,FALSE,0,0
Files upload in Spring using PUT method - testing and general idea,"<p>I am designing REST API of simple file storage where one of the operations is file upload that goes together with some file metadata (using ""multipart/form-data"").
For some cases I need the file ID to be generated out of my application so I use PUT Http method.  When ID goes from outside the best practice is to use PUT method instead of POST. The reason is that PUT operation is idempotent. POST is not idempotent and is used when ID is generated internally.</p>

<p>Do you think that going with PUT is correct for file upload? (I have also POST because ID is sometimes generated internally)</p>

<p>Assuming that it is correct I have an issue with automated integration testing in Spring. The problem is with MockMvc support class called MockMultipartHttpServletRequestBuilder when writing integration test. It does not allow to change POST to PUT. Http method is constructor parameter somewhere higher in inheritence hierarchy and the filed is ""private final"". All the constructors of these classes are with default visibility modifier so when I extend it I am not able to call super constructors. It is completly sealed.</p>

<p>Any idea how to achieve this call with PUT method? (I can use Java or Groovy for this)</p>

<pre><code>ResultActions response= mockMvc.perform(
        fileUpload(""/files"")
                .file(file)
                .param(""origin"", origin)
)
</code></pre>
",https://stackoverflow.com/questions/47925307/files-upload-in-spring-using-put-method-testing-and-general-idea,"['java', 'spring', 'rest', 'file-upload', 'groovy']",160,FALSE,0,0
REST API Testing with Citrus/Cucumber,"<p>I'm piloting use of Cucumber for functional/integration testing within my development organization and have been using Citrus with the standard glue it provides for API testing. The hurdle I've encountered is how to dynamically change the REST URL given variables for a scenario. The capability seems to exist in the Java DSL but is not exposed in the Cucumber steps. I can configure the citrus-http:client with placeholders for system properties but these obviously need to be resolved when the application context is loaded by Spring. What I'd like to be able to do in my Background message definition is something like:</p>

<pre><code>Given message todoListRequest
    And &lt;todoListRequest&gt; header Content-Type is ""application/json""
    And &lt;todoListRequest&gt; header Accept is ""application/json""
    And &lt;todoListRequest&gt; uri is ""/todo/${item-number}""
</code></pre>

<p>and then in a Scenario:</p>

<pre><code>Scenario: Gets expected item for specified item number
    Given variables 
        | item-number | 3 |
  When &lt;todoListClient&gt; sends message &lt;todoListRequest&gt;
  Then &lt;todoListClient&gt; should receive message &lt;todoListResponse&gt;
</code></pre>

<p>The service hostname and port could still be configured in the application context and the constructed URI appended to that value to create the target of the method (GET in this case, though I didn't specify and maybe that is something else that needs to be added?). Does that seem reasonable? Obviously, I could write my own glue for this but I wanted to see if there was an out of the box provided capability for what seems like a pretty obvious REST scenario before going that route. I understand the Cucumber integration is fairly recent (as of 2.6?) so it might still be maturing. This is an area where I would be interested in helping if that is welcome...</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/42418054/rest-api-testing-with-citrus-cucumber,['citrus-framework'],1402,TRUE,2,1
Integration tests sporadically timeout on Heroku hobby-dev,"<p>Since we do not get any helpful support from help.heroku.com we make the last try here.</p>

<p>We are developping a classic web app consisting of:</p>

<pre><code>    -----        -----        ----
    |WEB| &lt;----&gt; |API| &lt;----&gt; |DB|
    -----        -----        ----
</code></pre>

<p>We currently are working with the following Heroku Dynos/Datastores </p>

<ul>
<li>Heroku Postgres: Hobby Basic</li>
<li>Heroku API Dyno: Hobby</li>
<li>Heroku WEB Dyno: Hobby</li>
</ul>

<p>The tech stack is:</p>

<ul>
<li>runtime: nodejs (4.4.0)</li>
<li>db: postgres (9.6.1)</li>
<li>testframework: jasminejs (2.5.1)</li>
<li>query builder: knexjs (0.10.0)</li>
</ul>

<p>We recently moved to from self hosted docker environment to Heroku and configured the Herokus CI pipeline which works fine for unit testing - but not integration testing.
The tests sporadically fails with timeouts (in average every 3rd test of the same commit). This is not stable enough to build up CI/CD.</p>

<p>Here the error messages we get:</p>

<pre><code>**************************************************
*                    Failures                    *
**************************************************
1) integration test collections repository create() should return AUTHENTICATION_REQUIRED if user is anonymous
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
2) integration test collections repository create() should return AUTHORIZATION_REQUIRED if user is not space MEMBER
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
3) integration test collections repository create() should return collection if user is space MEMBER
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
</code></pre>

<p>For testing purposes we configured knex connection pooling to use one connection only:</p>

<pre><code>export default {
    client: 'pg',
    connection: DB_URL,
    pool: {
    max: 1,
    min: 1
    }
};
</code></pre>

<p>The typical integration test setup is:</p>

<pre><code>describe('integration test', () =&gt; {
    describe('collections repository create()', () =&gt; {
        //////////////////////////////////////////////////////////////////////
        //Before the test block is execute all fixtures are loaded into the DB
        //////////////////////////////////////////////////////////////////////
        beforeAll((callback) =&gt; {
            seed(path.join(__dirname, 'fixtures'))
            .then(callback)
            .catch((error) =&gt; {
                fail(error);
                callback();
            });
        });

        ////////////////////////////////////////////////////////////////////////
        //Truncate all data from the DB before the next test block gets executed
        ////////////////////////////////////////////////////////////////////////
        afterAll(resetDB);

        it('should return AUTHENTICATION_REQUIRED if user is anonymous', (callback) =&gt; {
            testUtils.testAsync({
                callback,
                catchTest: (error) =&gt; {
                    expect(error).toEqual(jasmine.any(repositoryErrors.AUTHENTICATION_REQUIRED));
                },
                runAsync: create({ props: { space: { id: 1 } } })
            });
        });

        it('should return AUTHORIZATION_REQUIRED if user is not space MEMBER', (callback) =&gt; {
            testUtils.testAsync({
                callback,
                catchTest: (error) =&gt; {
                    expect(error).toEqual(jasmine.any(repositoryErrors.AUTHORIZATION_REQUIRED));
                },
                runAsync: create({ props: { space: { id: 1 } }, userId: 1 })
            });
        });

        it('should return collection if user is space MEMBER', (callback) =&gt; {
            testUtils.testAsync({
                callback,
                runAsync: create({ props: { space: { id: 1 } }, userId: 2 }),
                thenTest: (outcome) =&gt; {
                    expect(outcome).toEqual({ id: '1' });
                }
            });
        });
    ...
</code></pre>

<p>seed:</p>

<pre><code>const tableOrder = [
    'users',
    'guidelines',
    'collections',
    'spaces',
    'details',
    'files',
    'guidelinesAuthors',
    'collectionsUsers',
    'spacesUsers',
    'guidelinesCollections',
    'spacesCollections',
    'guidelinesDetails',
    'guidelinesFiles',
    'comments',
    'commentsReplies',
    'notifications'
];

export default function seed(path) {
    return db.raw('BEGIN;')
    .then(() =&gt; {
        return tableOrder.reduce((promise, table) =&gt; {
        return promise
            .then(() =&gt; slurp({ path, table }))
            .then(() =&gt; {
                updateIdSequence(table)
                    .catch((error) =&gt; {
                        // eslint-disable-next-line no-console
                        console.log(
                            `Updating id sequence for table '${table}' failed! Error: `,
                            error.message
                            );
                    });
            });
        }, Promise.resolve()).then(() =&gt; db.raw('COMMIT;'));
    })
    .catch((error) =&gt; {
        // eslint-disable-next-line no-console
        console.log('SEED DATA FAILED', error);

        return db.raw('ROLLBACK;');
    });
}
...
</code></pre>

<p>resetDB:</p>

<pre><code>export default function resetDB(callback) {
    const sql = 'BEGIN; '
    + 'SELECT truncateAllData(); '
    + 'SELECT restartSequences(); '
    + 'COMMIT;';

    return db.raw(sql)
    .then(callback)
    .catch((error) =&gt; {
        // eslint-disable-next-line no-console
        console.log('TRUNCATE TABLES FAILED', error);

        return db.raw('ROLLBACK;');
    });
}
</code></pre>

<p>Until now, these test have been running on local machines (Linux/Mac) and Codeship without any problem.</p>

<p>After almost two weeks of trying to get this work we made zero progress on this issue. I can't see anything wrong with this configuration and I start to belive Heroku has a serious issue with the datastores...</p>

<p>Has anybody experienced similar issues on Heroku?
Any idea what we can try else to get this work?</p>
",https://stackoverflow.com/questions/45636916/integration-tests-sporadically-timeout-on-heroku-hobby-dev,"['node.js', 'postgresql', 'heroku', 'jasmine', 'timeout']",157,FALSE,1,0
several errors with sandbox.paypal.com?,"<p>I am trying to integrate paypal to my web app. I want to use paypal as payment gateway. In the process i am encountering various errors as listed below. </p>

<p>1) I logged into developer.paypal.com. When i click Accounts under Sandbox it lists all sandbox accounts i have. I wanted to delete the unused account but it says ""Something went wrong. One or more sandbox accounts could not be deleted. Try again."".</p>

<p>2) I created merchant or business account in developer.paypal.com. I then logged into sandbox.paypal.com using the created business account. In the dashboard page there is Tools at the top. I clicked on it and selected API credentials in order to get the api credentials for paypal integration to my web app. After clicking on it, it redirects me to my official paypal account dashboard page. i.e <a href=""https://www.paypal.com/myaccount/home"" rel=""nofollow noreferrer"">https://www.paypal.com/myaccount/home</a></p>

<p>3) Finally another issue i have been facing and of which i have not been able to receive any solution yet is described in detail here. <a href=""https://stackoverflow.com/questions/47716164/error-trying-to-make-sandbox-paypal-to-work-with-rails"">error trying to make sandbox paypal to work with rails?</a></p>

<p>So seeing all these issues i am wondering whether sandbox account is full of bugs and cannot be trusted for api integration testing. In that case does one recommend testing with real accounts? but that will be expensive because we need to send real money. </p>

<p>I appreciate any help on this dilemma. Thanks!</p>
",https://stackoverflow.com/questions/47746520/several-errors-with-sandbox-paypal-com,"['ruby-on-rails', 'paypal', 'paypal-sandbox']",41,FALSE,0,1
Spock script not compiling automatically in Spring MVC project which is using Eclipse IDE,"<p>I am working on a Spring based web project (Eclipse as IDE), in which we want to introduce integration testing framework using Spock.  This project is based on Maven.  For this purpose I have installed Greclipse plugin and converted the existing project to groovy nature.  Also configured Maven to run the test classes in src/test/groovy folder, and everything working fine and all the spock tests are running fine with run ""Maven test"" phase.  Configured the build path to compile the groovy test files to target/test-classes. </p>

<p>The problem is coming when I run the Spock tests using Run -> Run configuration.  It runs file with Junit runner using run configuration, it is picking up the compiled test class from target/test-classes.  Whenever I modify the Spock test script file, it is not automatically generating the classes, Run with Run Configuration is always picking up the old compiled class.</p>

<p>How to force the script to compile so that I don't always need to Maven clean and Maven test, to force it compile and run.</p>

<p>I have found in some other threads talking about modifying the Groovy compiler options to ""Enable script folder Support"", both checking and unchecking is of no use either.  Its not forcing the Spock script to compile (also tried enabling the same option in Eclipse Preferences global Groovy compiler option)</p>

<p>Any help is greatly appreciated. </p>
",https://stackoverflow.com/questions/42287407/spock-script-not-compiling-automatically-in-spring-mvc-project-which-is-using-ec,"['eclipse', 'spring', 'groovy', 'compilation', 'spock']",205,TRUE,0,1
Right way to terminate testing mongodb server,"<p>We are using <code>mongodb-prebuilt</code> package for perform unit/integration testing (CI/CD) for the developed software, which performs interaction with mongodb database.</p>

<p>Common use case is following: launch testing mongodb server with prebuild package, perform test suite execution and then terminate server. First and second items are done easily, but third one causes some problems.</p>

<p>If <code>mongodb-prebuilt</code>-started server had not been terminated, test runner will hang forever. Instead, if try to terminate server by <code>testConnection.command({ shutdown: 1 })</code> command, then <code>unhandledRejection</code> fires, which refers on closed connection - which of course had been forcefully closed by stopping the server.</p>

<p>Which is right way to dispose <code>mongodb-prebuilt</code> at <code>afterAll</code> test section? Test engine is <code>jest</code>, but it does not matter strongly.<br>
Example code here:</p>

<pre><code>import { MongodHelper } from 'mongodb-prebuilt';
import { MongoClient } from 'mongodb';

describe('Test suite', () =&gt; {
    let testConnection;
    beforeAll(async () =&gt; {
        const mongodHelper = new MongodHelper(['--port', ""27018""]);
        await mongodHelper.run();
        testConnection = await MongoClient.connect(`mongodb://localhost:27018/admin`);
    });
    afterAll(async () =&gt; {
        await testConnection.dropDatabase();
        await testConnection.command({ shutdown: 1 });
        await testConnection.close();
        testConnection = null;
    });
    /* Here follows some test suite that uses testConnection  */
}
</code></pre>

<p>There was some attempts to solve problem:</p>

<p>1) Don't await <code>testConnection.command({ shutdown: 1 })</code>-generated promise, and instantly initiate client connection closing - it works on some machines, but most likely depends on execution speed, so works unstable.</p>

<p>2) Because of client connection termination at the end of the tests does not matter strongly - it's possible to setup <code>process.on('unhandledRejection', ...)</code> handler in <code>afterAll</code> section and just mute exception - works well, but seems to be ideologically incorrect</p>

<p>So, maybe is there stereotypical solution for original task?</p>

<p><strong>IMPORTANT NOTE</strong>: suggesting use some mock packages instead live <code>mongodb</code> is not appropriate at all, since developed software is specific adapter for <code>mongodb</code> and should respect all aspects of live database, including timings, admin commands and so on</p>
",https://stackoverflow.com/questions/47976827/right-way-to-terminate-testing-mongodb-server,"['node.js', 'mongodb', 'testing']",985,FALSE,0,1
SSDT projects and managing Integration tests with known data,"<p>I'm migrating over to SSDT for schema control of the DB structure for a large project with accompanying database. This project already has hundreds of integration tests inside of it that are in various states of brittleness. Many of these use what I would call ""known data"" to perform the integration tests with. The tests are relying on this data to be there for them to run successfully. </p>

<p>In the past, we've done a 1:1 copy of our integration test database for testing in feature branches, but i'm not wild about this process as it adds bloat to the server.</p>

<p>Using SSDT, is there a way to incorporate this ""known data"" into either a SSDT project, or a process that can be used to copy after the fact? I already have post-deploy scripts that load seed data into the system (types and the like), so I could put all known data there, but this could be dozens of extra sql files to potentially manage so i'm not wild about it.</p>

<p>Due to the complexities and the amount of known data, using the application sitting on top of the DB to insert it is not practical. </p>

<p>I was thinking about exploring a bacpac option, but before doing that wanted to see if there were any other ways people have managed integration testing of feature branches with known data in the past.</p>
",https://stackoverflow.com/questions/44888562/ssdt-projects-and-managing-integration-tests-with-known-data,"['sql-server', 'integration-testing', 'sql-server-data-tools']",615,TRUE,0,3
I cannot get the latest meteor todos example chimp acceptance test to work on mac osx 10.11.16 with chrome Version 59.0.3071.86,"<p>I am running on OSX 10.11.6 with Chrome Version 59.0.3071.86 (Official Build) (64-bit) and I have downloaded and installed the latest meteor todos app, and following the tutorial performed the unit and integration testing examples successfully. When I try the chimp acceptance test and use --debug in the output I get the first log below which indicates a browser incompatibility. After changing the 
node_modules/chimp/dist/bin/default.js seleniumStandaloneOptions 
like this (notice version: 2.30)...</p>

<pre><code>  seleniumStandaloneOptions: {
    // check for more recent versions of selenium here:
    // http://selenium-release.storage.googleapis.com/index.html
    version: '3.0.1',
    baseURL: 'https://selenium-release.storage.googleapis.com',
    drivers: {
      chrome: {
        // check for more recent versions of chrome driver here:
        // http://chromedriver.storage.googleapis.com/index.html
        //version: '2.25',
        version: '2.30',
        arch: process.arch,
        baseURL: 'https://chromedriver.storage.googleapis.com'
      },
</code></pre>

<p>.....
I get the second log below. 
I do see a window flash briefly then go away - too fast to see what it is doing. There is no output on the meteor console either. I have tried many different options but cannot seem to make this work, and do not seem to know how to debug it. Do any of you have any other ideas or debugging help? The browser can exercise the todos app on localhost:3000 with no apparent problems. There are no console errors in the browser while it is accessing the todos app. 
I would really appreciate any insight anyone has. Thanks.</p>

<p>First log.....</p>

<pre><code>$chimp --ddp=http://localhost:3000 --test --mocha --path=tests --debug
[chimp] Chimp options are { watch: false,
  watchTags: '@watch,@focus',
  domainSteps: null,
  e2eSteps: null,
  fullDomain: false,
  domainOnly: false,
  e2eTags: '@e2e',
  watchWithPolling: false,
  server: false,
  serverPort: 8060,
  serverHost: 'localhost',
  sync: true,
  offline: false,
  showXolvioMessages: true,
  'fail-when-no-tests-run': false,
  path: './features',
  format: 'pretty',
  tags: '~@ignore',
  singleSnippetPerFile: true,
  recommendedFilenameSeparator: '_',
  chai: false,
  screenshotsOnError: false,
  screenshotsPath: '.screenshots',
  captureAllStepScreenshots: false,
  saveScreenshotsToDisk: true,
  saveScreenshotsToReport: false,
  jsonOutput: null,
  compiler: 'js:/usr/local/lib/node_modules/chimp/dist/lib/babel-register.js',
  conditionOutput: true,
  browser: null,
  platform: 'ANY',
  name: '',
  user: '',
  key: '',
  port: null,
  host: null,
  webdriverio: 
   { desiredCapabilities: {},
     logLevel: 'silent',
     host: '127.0.0.1',
     port: 4444,
     path: '/wd/hub',
     baseUrl: null,
     coloredLogs: true,
     screenshotPath: null,
     waitforTimeout: 500,
     waitforInterval: 250 },
  seleniumStandaloneOptions: 
   { version: '3.0.1',
     baseURL: 'https://selenium-release.storage.googleapis.com',
     drivers: { chrome: [Object], ie: [Object], firefox: [Object] } },
  noSessionReuse: false,
  simianResultEndPoint: 'api.simian.io/v1.0/result',
  simianAccessToken: false,
  simianResultBranch: null,
  simianRepositoryId: null,
  mocha: false,
  mochaCommandLineOptions: { bail: true },
  mochaConfig: 
   { tags: '',
     grep: null,
     timeout: 60000,
     reporter: 'spec',
     slow: 10000,
     useColors: true },
  jasmine: false,
  jasmineConfig: 
   { specDir: '.',
     specFiles: [ '**/*@(_spec|-spec|Spec).@(js|jsx)' ],
     helpers: [ 'support/**/*.@(js|jsx)' ],
     stopSpecOnExpectationFailure: false,
     random: false },
  jasmineReporterConfig: {},
  ddp: false,
  serverExecuteTimeout: 10000,
  phantom_w: 1280,
  phantom_h: 1024,
  phantom_ignoreSSLErrors: false,
  log: 'info',
  debug: false,
  seleniumDebug: null,
  debugCucumber: null,
  debugBrkCucumber: null,
  debugMocha: null,
  debugBrkMocha: null }

Chimp version:  0.49.0
ChromeDriver version:  ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262)
Java version:  java version ""1.8.0_66"", Java(TM) SE Runtime Environment (build 1.8.0_66-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)
Selenium version:  3.0.1
Selenium drivers version:  chrome: 2.25, ie: 2.50.0, firefox: 0.11.1
OS version:  Darwin 15.6.0
Node version:  v6.11.0
[chimp][browserdriver] starting process
[chimp][browserdriver.stdout] Starting ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262) on port 52347
Only local connections are allowed.

[chimp][browserdriver] started successfully
[chimp][browserdriver] kill called on browserdriver process with pid 48946
[chimp][browserdriver] checking if process exists
[chimp][browserdriver] browserdriver process exists, killing it with SIGTERM
[chimp][browserdriver] waiting for process to die (0/10)
[chimp][browserdriver] process is dead
Browser version:  chrome undefined

[chimp] Running...
[chimp] interrupting
[chimp] no processes to interrupt
[chimp][chromedriver] starting process
[chimp][chromedriver.stdout] Starting ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262) on port 52347
Only local connections are allowed.

[chimp][chromedriver] started successfully
[chimp][mocha] Running...


[chimp][helper] Using the chai-expect assertion library
[chimp][ddp] creating DDP wrapper
[chimp][ddp] Connecting to DDP server { host: 'localhost',
  port: '3000',
  ssl: false,
  path: undefined,
  autoReconnect: true,
  autoReconnectTimer: 500,
  maintainCollections: true,
  ddpVersion: '1',
  useSockJs: true }
[chimp][ddp] creating DDP wrapper
[chimp][ddp] Connecting to DDP server { host: 'localhost',
  port: '3000',
  ssl: false,
  path: undefined,
  autoReconnect: true,
  autoReconnectTimer: 500,
  maintainCollections: true,
  ddpVersion: '1',
  useSockJs: true }
[chimp][helper] getting browser
[chimp][session-manager-factory] options are { host: 'localhost',
  port: 52347,
  user: undefined,
  key: undefined,
  browser: 'chrome',
  deviceName: undefined }
[chimp][session-manager] created a new SessionManager
[chimp][helper] webdriverioOptions are  {""desiredCapabilities"":{""browserName"":""chrome"",""platform"":""ANY"",""name"":""""},""logLevel"":""verbose"",""host"":""localhost"",""port"":52347,""path"":""/wd/hub"",""baseUrl"":null,""coloredLogs"":true,""screenshotPath"":null,""waitforTimeout"":500,""waitforInterval"":250,""sync"":true}
[chimp][session-manager] creating webdriver remote 
[chimp][session-manager] checking connection to selenium server
[15:10:45]  COMMAND GET      ""/wd/hub/status""
[15:10:45]  DATA        {}
[15:10:45]  RESULT      {""build"":{""version"":""alpha""},""os"":{""arch"":""x86_64"",""name"":""Mac OS X"",""version"":""10.11.6""}}
[chimp][session-manager] Connection to the to selenium server verified
[chimp][session-manager] watch mode is false, not reusing a session
[chimp][hooks] init browser
[chimp][hooks] init browser callback
[15:10:45]  COMMAND POST     ""/wd/hub/session""
[15:10:45]  DATA        {""desiredCapabilities"":{""javascriptEnabled"":true,""locationContextEnabled"":true,""handlesAlerts"":true,""rotatable"":true,""browserName"":""chrome"",""platform"":""ANY"",""name"":"""",""loggingPrefs"":{""browser"":""ALL"",""driver"":""ALL""},""requestOrigins"":{""url"":""http://webdriver.io"",""version"":""4.6.2"",""name"":""webdriverio""}}}
[chimp][helper] setupBrowserAndDDP had error
{ Error: session not created exception: Chrome version must be &gt;= 58.0.3029.0
    at initBrowser (/usr/local/lib/node_modules/chimp/dist/lib/chimp-helper.js:189:43)
    at Object.setupBrowserAndDDP (/usr/local/lib/node_modules/chimp/dist/lib/chimp-helper.js:264:7)
    at Context.&lt;anonymous&gt; (/usr/local/lib/node_modules/chimp/dist/lib/mocha/mocha-helper.js:13:15)
    at /usr/local/lib/node_modules/chimp/dist/lib/utils/fiberize.js:29:22
    (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)
  message: 'session not created exception: Chrome version must be &gt;= 58.0.3029.0\n  (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)',
  type: 'RuntimeError',
  seleniumStack: 
   { status: 33,
     type: 'SessionNotCreatedException',
     message: 'A new session could not be created.',
     orgStatusMessage: 'session not created exception: Chrome version must be &gt;= 58.0.3029.0\n  (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)' } }
Error: session not created exception: Chrome version must be &gt;= 58.0.3029.0
    at initBrowser (/usr/local/lib/node_modules/chimp/dist/lib/chimp-helper.js:189:43)
    at Object.setupBrowserAndDDP (/usr/local/lib/node_modules/chimp/dist/lib/chimp-helper.js:264:7)
    at Context.&lt;anonymous&gt; (/usr/local/lib/node_modules/chimp/dist/lib/mocha/mocha-helper.js:13:15)
    at /usr/local/lib/node_modules/chimp/dist/lib/utils/fiberize.js:29:22
    (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)
[chimp][mocha] Closed with code 2
[chimp][mocha] Mocha not in a stopping state
[chimp] Finished running async processes with errors
[chimp] run complete with errors Mocha failed
[chimp] interrupting
[chimp] 2 processes to interrupt
[chimp][mocha] interrupting mocha
[chimp][mocha] kill called on mocha process with pid 48957
[chimp][mocha] checking if process exists
[chimp][mocha] mocha process does not exists, ignoring
[chimp][chromedriver] interrupt called
[chimp][chromedriver] stopping process
[chimp][chromedriver] kill called on chromedriver process with pid 48956
[chimp][chromedriver] checking if process exists
[chimp][chromedriver] chromedriver process exists, killing it with SIGTERM
Mocha failed
Error in chimp init Mocha failed
</code></pre>

<p>.......
Second log with chromedriver v 2.30.....</p>

<pre><code>$chimp --ddp=http://localhost:3000 --test --mocha --path=tests --debug
[chimp] Chimp options are { watch: false,
  watchTags: '@watch,@focus',
  domainSteps: null,
  e2eSteps: null,
  fullDomain: false,
  domainOnly: false,
  e2eTags: '@e2e',
  watchWithPolling: false,
  server: false,
  serverPort: 8060,
  serverHost: 'localhost',
  sync: true,
  offline: false,
  showXolvioMessages: true,
  'fail-when-no-tests-run': false,
  path: './features',
  format: 'pretty',
  tags: '~@ignore',
  singleSnippetPerFile: true,
  recommendedFilenameSeparator: '_',
  chai: false,
  screenshotsOnError: false,
  screenshotsPath: '.screenshots',
  captureAllStepScreenshots: false,
  saveScreenshotsToDisk: true,
  saveScreenshotsToReport: false,
  jsonOutput: null,
  compiler: 'js:/usr/local/lib/node_modules/chimp/dist/lib/babel-register.js',
  conditionOutput: true,
  browser: null,
  platform: 'ANY',
  name: '',
  user: '',
  key: '',
  port: null,
  host: null,
  webdriverio: 
   { desiredCapabilities: {},
     logLevel: 'silent',
     host: '127.0.0.1',
     port: 4444,
     path: '/wd/hub',
     baseUrl: null,
     coloredLogs: true,
     screenshotPath: null,
     waitforTimeout: 500,
     waitforInterval: 250 },
  seleniumStandaloneOptions: 
   { version: '3.0.1',
     baseURL: 'https://selenium-release.storage.googleapis.com',
     drivers: { chrome: [Object], ie: [Object], firefox: [Object] } },
  noSessionReuse: false,
  simianResultEndPoint: 'api.simian.io/v1.0/result',
  simianAccessToken: false,
  simianResultBranch: null,
  simianRepositoryId: null,
  mocha: false,
  mochaCommandLineOptions: { bail: true },
  mochaConfig: 
   { tags: '',
     grep: null,
     timeout: 60000,
     reporter: 'spec',
     slow: 10000,
     useColors: true },
  jasmine: false,
  jasmineConfig: 
   { specDir: '.',
     specFiles: [ '**/*@(_spec|-spec|Spec).@(js|jsx)' ],
     helpers: [ 'support/**/*.@(js|jsx)' ],
     stopSpecOnExpectationFailure: false,
     random: false },
  jasmineReporterConfig: {},
  ddp: false,
  serverExecuteTimeout: 10000,
  phantom_w: 1280,
  phantom_h: 1024,
  phantom_ignoreSSLErrors: false,
  log: 'info',
  debug: false,
  seleniumDebug: null,
  debugCucumber: null,
  debugBrkCucumber: null,
  debugMocha: null,
  debugBrkMocha: null }

Chimp version:  0.49.0
ChromeDriver version:  ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262)
Java version:  java version ""1.8.0_66"", Java(TM) SE Runtime Environment (build 1.8.0_66-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)
Selenium version:  3.0.1
Selenium drivers version:  chrome: 2.25, ie: 2.50.0, firefox: 0.11.1
OS version:  Darwin 15.6.0
Node version:  v6.11.0
[chimp][browserdriver] starting process
[chimp][browserdriver.stdout] Starting ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262) on port 52418
Only local connections are allowed.

[chimp][browserdriver] started successfully
[chimp][browserdriver] kill called on browserdriver process with pid 49380
[chimp][browserdriver] checking if process exists
[chimp][browserdriver] browserdriver process exists, killing it with SIGTERM
[chimp][browserdriver] waiting for process to die (0/10)
[chimp][browserdriver] process is dead
Browser version:  chrome undefined

[chimp] Running...
[chimp] interrupting
[chimp] no processes to interrupt
[chimp][chromedriver] starting process
[chimp][chromedriver.stdout] Starting ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262) on port 52418
Only local connections are allowed.

[chimp][chromedriver] started successfully
[chimp][mocha] Running...


[chimp][helper] Using the chai-expect assertion library
[chimp][ddp] creating DDP wrapper
[chimp][ddp] Connecting to DDP server { host: 'localhost',
  port: '3000',
  ssl: false,
  path: undefined,
  autoReconnect: true,
  autoReconnectTimer: 500,
  maintainCollections: true,
  ddpVersion: '1',
  useSockJs: true }
[chimp][ddp] creating DDP wrapper
[chimp][ddp] Connecting to DDP server { host: 'localhost',
  port: '3000',
  ssl: false,
  path: undefined,
  autoReconnect: true,
  autoReconnectTimer: 500,
  maintainCollections: true,
  ddpVersion: '1',
  useSockJs: true }
[chimp][helper] getting browser
[chimp][session-manager-factory] options are { host: 'localhost',
  port: 52418,
  user: undefined,
  key: undefined,
  browser: 'chrome',
  deviceName: undefined }
[chimp][session-manager] created a new SessionManager
[chimp][helper] webdriverioOptions are  {""desiredCapabilities"":{""browserName"":""chrome"",""platform"":""ANY"",""name"":""""},""logLevel"":""verbose"",""host"":""localhost"",""port"":52418,""path"":""/wd/hub"",""baseUrl"":null,""coloredLogs"":true,""screenshotPath"":null,""waitforTimeout"":500,""waitforInterval"":250,""sync"":true}
[chimp][session-manager] creating webdriver remote 
[chimp][session-manager] checking connection to selenium server
[15:16:54]  COMMAND GET      ""/wd/hub/status""
[15:16:54]  DATA        {}
[15:16:54]  RESULT      {""build"":{""version"":""alpha""},""os"":{""arch"":""x86_64"",""name"":""Mac OS X"",""version"":""10.11.6""}}
[chimp][session-manager] Connection to the to selenium server verified
[chimp][session-manager] watch mode is false, not reusing a session
[chimp][hooks] init browser
[chimp][hooks] init browser callback
[15:16:54]  COMMAND POST     ""/wd/hub/session""
[15:16:54]  DATA        {""desiredCapabilities"":{""javascriptEnabled"":true,""locationContextEnabled"":true,""handlesAlerts"":true,""rotatable"":true,""browserName"":""chrome"",""platform"":""ANY"",""name"":"""",""loggingPrefs"":{""browser"":""ALL"",""driver"":""ALL""},""requestOrigins"":{""url"":""http://webdriver.io"",""version"":""4.6.2"",""name"":""webdriverio""}}}
[chimp][helper] setupBrowserAndDDP had error
{ Error: session not created exception: Chrome version must be &gt;= 58.0.3029.0
    at initBrowser (/usr/local/lib/node_modules/chimp/dist/lib/chimp-helper.js:189:43)
    at Object.setupBrowserAndDDP (/usr/local/lib/node_modules/chimp/dist/lib/chimp-helper.js:264:7)
    at Context.&lt;anonymous&gt; (/usr/local/lib/node_modules/chimp/dist/lib/mocha/mocha-helper.js:13:15)
    at /usr/local/lib/node_modules/chimp/dist/lib/utils/fiberize.js:29:22
    (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)
  message: 'session not created exception: Chrome version must be &gt;= 58.0.3029.0\n  (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)',
  type: 'RuntimeError',
  seleniumStack: 
   { status: 33,
     type: 'SessionNotCreatedException',
     message: 'A new session could not be created.',
     orgStatusMessage: 'session not created exception: Chrome version must be &gt;= 58.0.3029.0\n  (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)' } }
Error: session not created exception: Chrome version must be &gt;= 58.0.3029.0
    at initBrowser (/usr/local/lib/node_modules/chimp/dist/lib/chimp-helper.js:189:43)
    at Object.setupBrowserAndDDP (/usr/local/lib/node_modules/chimp/dist/lib/chimp-helper.js:264:7)
    at Context.&lt;anonymous&gt; (/usr/local/lib/node_modules/chimp/dist/lib/mocha/mocha-helper.js:13:15)
    at /usr/local/lib/node_modules/chimp/dist/lib/utils/fiberize.js:29:22
    (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)
[chimp][mocha] Closed with code 2
[chimp][mocha] Mocha not in a stopping state
[chimp] Finished running async processes with errors
[chimp] run complete with errors Mocha failed
[chimp] interrupting
[chimp] 2 processes to interrupt
[chimp][mocha] interrupting mocha
[chimp][mocha] kill called on mocha process with pid 49391
[chimp][mocha] checking if process exists
[chimp][mocha] mocha process does not exists, ignoring
[chimp][chromedriver] interrupt called
[chimp][chromedriver] stopping process
[chimp][chromedriver] kill called on chromedriver process with pid 49390
[chimp][chromedriver] checking if process exists
[chimp][chromedriver] chromedriver process exists, killing it with SIGTERM
Mocha failed
Error in chimp init Mocha failed
</code></pre>

<p>.......</p>

<p>I really want to get chimp working in order to implement acceptance testing on a significant meteor project that we are using in my group.</p>

<p>Failing getting chimp to work, if anyone knows of a better way to do automated acceptance testing on a meteor app I would appreciate that insight as well. Thanks.</p>
",https://stackoverflow.com/questions/44640410/i-cannot-get-the-latest-meteor-todos-example-chimp-acceptance-test-to-work-on-ma,"['javascript', 'macos', 'google-chrome', 'meteor', 'chimp.js']",206,FALSE,-1,1
SpringBootTest mock Authentication Principal with a custom User does not work,"<p>I am using Spring Boot 1.4.2 and I am new with Spring Boot. 
I have an Authentication Filter to set the current user information when the user log in. 
In an advice for the controller, I made the call to get the current userId as below: </p>

<pre><code>public static String getCurrentUserToken(){
    return ((AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserId();
}
</code></pre>

<p>Here is my custom AuthenticatedUser:</p>

<pre><code>public class AuthenticatedUser implements Serializable {

private final String userName;
private final String userId;
private final String sessionId;

public AuthenticatedUser(String userName, String userId, String sessionId) {
    super();
    this.userName = userName;
    this.userId = userId;
    this.sessionId = sessionId;
}

public String getUserName() {
    return userName;
}

public String getUserId() {
    return userId;
}

public String getSessionId() {
    return sessionId;
}
</code></pre>

<p>}</p>

<p>Everything works fine. 
However, the filter does not work in integration testing and I need to mock a current user. 
I searched a lot on how to mock a user but none of them help me. I finally found out this guide  which is likely close to what I wanted: <a href=""https://aggarwalarpit.wordpress.com/2017/05/17/mocking-spring-security-context-for-unit-testing/"" rel=""nofollow noreferrer"">https://aggarwalarpit.wordpress.com/2017/05/17/mocking-spring-security-context-for-unit-testing/</a> 
Below is my testing class following that guideline:</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class PersonalLoanPreApprovalTest {

@Before
public void initDB() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testRequestPersonalLoanPreApproval_Me() {
  AuthenticatedUser applicationUser = new 
  AuthenticatedUser(""test@abc.com"", ""2d1b5ae3"", ""123"");
  UsernamePasswordAuthenticationToken authentication = new ApiKeyAuthentication(applicationUser);
  SecurityContext securityContext = mock(SecurityContext.class);

  when(securityContext.getAuthentication()).thenReturn(authentication);
  SecurityContextHolder.setContext(securityContext);

  // error at this line
  when(securityContext.getAuthentication().getPrincipal()) .thenReturn(applicationUser); 

  // The controller for this api has the advice to get the userId
  MyResponse response = restTemplate.getForObject(url.toString(), MyResponse.class);
}
}
</code></pre>

<p>I got this error:</p>

<pre><code>org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
AuthenticatedUser cannot be returned by getAuthentication()
getAuthentication() should return Authentication
</code></pre>

<p>I spent couple days on this already, tried a lot of suggestions I found but still failed. I also tried to remove the line that cause error, but when the error gone, I still could not get the current user information in my controller advice.</p>

<p>Any suggestion is highly appreciated. </p>

<p><strong>UPDATE1:</strong> Just wanted to have my results with some modification in the code.</p>

<p>With @glitch suggestion, I changed the code to mock the authentication and user in my test method as below:</p>

<pre><code> @Test
 public void testRequestPersonalLoanPreApproval_Me() {
    AuthenticatedUser applicationUser = new AuthenticatedUser(""testtu_free@cs.com"", ""2d1b5ae3-cf04-44f5-9493-f0518cab4554"", ""123"");
    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getPrincipal()).thenReturn(applicationUser);      

  // The controller for this api has the advice to get the userId
  MyResponse response = restTemplate.getForObject(url.toString(), MyResponse.class);
}
}
</code></pre>

<p>I now can get rid of the error in the testing class. I debugged into the code, see that the securityContext has value when I am in the testing class. But when I jump to the code inside the controller advice, the below get returns null: </p>

<pre><code>SecurityContextHolder.getContext().getAuthentication().getPrincipal()
</code></pre>
",https://stackoverflow.com/questions/46615504/springboottest-mock-authentication-principal-with-a-custom-user-does-not-work,"['java', 'authentication', 'spring-boot', 'mockito']",17532,TRUE,5,2
Testing - How this common scenario is classified and handled,"<p>I’m just diving into testing/test driven development in php, and am a bit confused about how to handle a very typical scenario in our legacy codebase. Our codebase does not have many classes, it’s very functional programming oriented.</p>

<p>In this example code, which is pseudocode, I want to write a test for getAndOrderUsersByAge(). As you can see it first gets all the users from our database (in a giant array lets say, because we don’t have objects/classes) then sorts them. This is of course a VERY common occurrence in our code, manipulating or analyzing data gotten from the database; not objects, but an array of database rows basically.</p>

<p>Note that I've added an error in the if statement to simulate an error I want my tests to catch.</p>

<pre><code>//gets all users in our db into an array, then sorts them by age
function getAndOrderUsersByAge(){
     //get all users from the db
     $all_users = getAllUsers();

     //sort
     $all_users_sorted = sortUsers($all_users)

     //notice I've made a mistake here on purpose, left the ""d"" off of ""$all_users_sorted""
     //so the function will always return false, a mistake...which I want tests to catch
     if(!empty($all_users_sorte){
         return $all_users_sorted;
     }
     else{
         return false;
     }
}
</code></pre>

<p>My questions are:</p>

<p>1.) Is testing the function getAndOrderUsersByAge() unit testing, integration testing, or …?</p>

<p>2.) In my (unit?) test(s) of getAndOrderUsersByAge(), I want to assume that getAllUsers (the function which gets things from the db) behaves correctly because I only want to test getAndOrderUsersByAge() right? I’m not really sure what “concept” this falls under when I’m reading the two books I have on testing. Is this where I would “mock”, e.g. create some fake data for getAllUsers() to return?</p>

<p>3.) What tests would you write for getAndOrderUsersByAge()? I think I would write one that ensures a non-empty array is returned when getAllUsers() returns a non-empty array, as this would catch the error I've created. I'm not sure what else though.</p>

<p>Any tips, recommended reading material, etc. is very welcomed.</p>
",https://stackoverflow.com/questions/47541884/testing-how-this-common-scenario-is-classified-and-handled,"['php', 'unit-testing', 'testing', 'integration-testing']",30,TRUE,0,1
Integration test an API whose behavior depends on the current time,"<p>I have a few APIs I'm trying to thoroughly <strong><em>integration</em></strong> test -- I'm hitting the remote service which is running in a test environment (not the same box that is running the tests, the tests make real service calls), I can't just use dependency injection to solve all my problems. We already have a good suite of unit tests on these classes.</p>

<p>The API I'm testing is SaveThingy. It saves a Thingy if it's valid, and returns you the id of it. One of the checks is that you can only save a thingy at certain times, say only on weekdays. If you call SaveThingy on the weekend, it insults you personally instead of saving a Thingy. The implementation looks something like the following</p>

<pre><code>ThingyId saveThingy(Thingy thingy) {
    if (isWeekend(LocalDate.now().getDayOfWeek())) {
        throw new PersonalInsultException(""your mother wears army boots"");
    }
    return thingyDao.save(thingy);
}
</code></pre>

<p>I'd ideally like to have both cases tested each time we run integration tests, without any waiting. In some code, I want tests similar to the following to run each time.</p>

<pre><code>@Test
public void saveThingy_validThingyOnWeekday_savesThingy() {
    ThingyId id = serviceUnderTest.saveThingy(THINGY);
    assertThat(serviceUnderTest.getThingyById(id)).isEqualTo(THINGY);
}

@Test(expected = PersonalInsultException.class)
public void saveThingy_validThingyOnWeekend_receivePersonalInsult() {
    serviceUnderTest.saveThing(THINGY);
}
</code></pre>

<p>Are there any standard ways that allow complete testing of such APIs? I've considered a few options (below), but wanted to get additional opinions.</p>

<ol>
<li>say no to integration testing, live with only unit tests for these APIs</li>
<li>change the remote clock, either using a private API or by literally ssh-ing into the host before running each test</li>
<li>write tests that are time dependent; only testing one of the possible behaviors, or testing one behavior then sleeping until other conditions are met</li>
<li>invent dummy data that will always save or always throw an exception</li>
</ol>
",https://stackoverflow.com/questions/46368059/integration-test-an-api-whose-behavior-depends-on-the-current-time,"['java', 'rest', 'testing', 'time', 'integration-testing']",876,TRUE,0,3
How can I add an extension that uses the internal Gollum markdown processor?,"<ul>
<li><p>Description:</p>

<ul>
<li>I am trying to integrate a workflow and tools which incorporates vimwiki and Gollum. I want to merely add vimwiki as an extention type for the editor while being processed by Gollum's internal Markdown processor (see ""Things I've tried"" #1). </li>
<li>Eventually I'd also like to have Gollum default to 'vimwiki' when creating new documents as well.</li>
<li>The project I'm working on can be found at <a href=""https://github.com/karlredman/Vimwiki-Gollum-Integration"" rel=""nofollow noreferrer"">Vimwiki-Gollum-Integration</a></li>
</ul></li>
<li><p>Testing Specifics:</p>

<ul>
<li>Gollum version: 4.1.1</li>
<li>The file being tested is valid github markdown</li>
<li>The same content is being tested with different filenames and extensions:

<ul>
<li>testx.thing</li>
<li>blah.vimwiki</li>
</ul></li>
<li>The test files do work fine when they are named with .md extensions</li>
<li>relevant rendering gems installed: 

<ul>
<li>github-markdown</li>
<li>github-markup</li>
<li>kramdown</li>
<li>redcarpet</li>
</ul></li>
<li>All code is being tested in a gollum --config  file</li>
<li>I'm not well versed in ruby</li>
</ul></li>
</ul>

<h2>Things I've tried</h2>

<ol>
<li>Creating a new extension and custom renderer

<ul>
<li>This works except there is no reason to implement a custom processor (pandoc)</li>
<li>This would be ideal so that the Markdown name ends up in the Edit page. However, I don't think I should have to involve pandoc here</li>
<li>How in the heck do I get the edit page to default the markdown to vimwiki when editing a vimwiki extension?</li>
<li>file used: blah.vimwiki</li>
</ul></li>
</ol>

<pre class=""lang-rb prettyprint-override""><code># always include this:
Gollum::Page.send :remove_const, :FORMAT_NAMES if defined? Gollum::Page::FORMAT_NAMES

################### custom extension + renderer
# # Custom extension rendering
# ## References
# * file reference: /var/lib/gems/2.1.0/gems/github-markup-1.6.0/lib/github/markup/command_implementation.rb
# * [Adding Pandoc to Gollum - Martin Wolf's weblog [OUTDATED]](https://www.mwolf.net/2014/04/29/adding-pandoc-to-gollum/)
ci = ::GitHub::Markup::CommandImplementation.new(
     /vimwiki/,
     [""Vimwiki""],
     ""pandoc -f markdown-tex_math_dollars-raw_tex"",
     :vimwiki)

# bind your own extension regex (the new set of extensions will also include `.asc` and `.adoc`):
# # * file reference: /var/lib/gems/2.1.0/gems/github-markup-1.6.0/lib/github/markups.rb
Gollum::Markup.register(:vimwiki,  ""Vimwiki"")
Gollum::Markup.formats[:vimwiki][:regexp] = /vimwiki/
GitHub::Markup::markup_impl(:vimwiki, ci)
##################
</code></pre>

<ol start=""2"">
<li>Attempt to replace the Markdown primary extension and regex.

<ul>
<li>I don't understand why this isn't working unless I'm misunderstanding the order of operations for matching and overrides.</li>
<li>The page will display, the extension is recognized, but the page does not format at all -scrunches everything together.</li>
</ul></li>
</ol>

<pre class=""lang-rb prettyprint-override""><code># always include this:
Gollum::Page.send :remove_const, :FORMAT_NAMES if defined? Gollum::Page::FORMAT_NAMES

# Attempt to replace the primary extension for Markdown
# remove the original markdown binding:
Gollum::Markup.formats.delete(:markdown)

# and define your own 
Gollum::Markup.formats[:thing] = {
    :name =&gt; ""Markdown"",
    :regexp =&gt; /thing/
}
</code></pre>

<ol start=""3"">
<li>Attempt to just replace the markdown extension regex

<ul>
<li>Same result as attempt 2.</li>
<li>The page will display but it is not formatted correctly</li>
</ul></li>
</ol>

<pre class=""lang-rb prettyprint-override""><code># always include this:
Gollum::Page.send :remove_const, :FORMAT_NAMES if defined? Gollum::Page::FORMAT_NAMES

Gollum::Markup.formats[:markdown][:regexp] = /vimwiki|thing/
</code></pre>
",https://stackoverflow.com/questions/45230393/how-can-i-add-an-extension-that-uses-the-internal-gollum-markdown-processor,"['ruby', 'gollum-wiki']",531,TRUE,3,1
How to reliably use a local Maven mirroring proxy with docker-compose?,"<p>I am working to migrate our Maven build process into Docker for our existing Java projects.  I am an experienced Java developer using Maven, but still learning Docker.</p>

<p>Our primary problem is that by default artifacts are not cached so we download half the Internet every five minutes, combined with we also have things on a local elderly Nexus server.     As this is for automated integration testing we do not want to build the artifacts outside of docker.</p>

<p>After careful consideration I found that a good solution could be to have a Maven mirroring proxy running for each developer where the local configuration can be kept and the Docker instances then just refer to that.   Manually running a Nexus3 container with</p>

<pre><code>docker run -p 8081:8081 --name nexus sonatype/nexus3
</code></pre>

<p>(plus some manual configuration to proxy our internal repository too) has worked very well so far, but is not controlled by docker-compose.   </p>

<p>Unfortunately I cannot see a way for the guests to access the host (where port 8081 is available) other than hardcoding the external IP-number of the machine, and I cannot see a way to make docker-compose responsible for ensuring that the nexus container is running when my docker builds needs it.</p>

<p>I am currently using this as the settings.xml file inside docker:</p>

<pre><code>&lt;settings xmlns=""http://maven.apache.org/SETTINGS/1.0.0""
          xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
          xsi:schemaLocation=""http://maven.apache.org/SETTINGS/1.0.0
                      https://maven.apache.org/xsd/settings-1.0.0.xsd""&gt;
    &lt;mirrors&gt;
        &lt;mirror&gt;
            &lt;id&gt;local-nexus&lt;/id&gt;
            &lt;name&gt;Local Nexus&lt;/name&gt;
            &lt;!-- Host external IP number --&gt;
            &lt;url&gt;http://1.2.3.4:8081/repository/sbforge_central/&lt;/url&gt;
            &lt;mirrorOf&gt;central&lt;/mirrorOf&gt;
        &lt;/mirror&gt;
    &lt;/mirrors&gt;
    &lt;localRepository&gt;/usr/share/maven/ref/repository&lt;/localRepository&gt;
&lt;/settings&gt;
</code></pre>

<p>How should I approach this?  I see two scenarios.</p>

<ol>
<li><p>How can I get a reliable name for the host?   Linux is required, other platforms will be nice.</p></li>
<li><p>How can I make docker-compose control this container so it is up when running <code>docker-compose build</code> so docker can ensure that the hostname of the nexus container resolves?  It is not needed when bringing the finished containers up.</p></li>
</ol>

<p>Or is there a smarter way?</p>
",https://stackoverflow.com/questions/47016186/how-to-reliably-use-a-local-maven-mirroring-proxy-with-docker-compose,"['java', 'maven', 'docker', 'proxy', 'maven-mirroring']",2143,TRUE,2,3
C++ desktop GUI testing on Travis CI,"<p>I enjoy Travis CI a lot for continuous integration testing. I test most of my C++ console, desktop (Qt, SFML) and web (using Wt) applications with it. It is great for testing browser-based applications <a href=""https://docs.travis-ci.com/user/gui-and-headless-browsers/"" rel=""nofollow noreferrer"">and has documented this nicely</a>.</p>

<p>One thing I cannot do is test the GUI of a desktop application on Travis CI. </p>

<p>I need basic things like 'get a window with a certain title/name its size', 'click left mouse button in the center' of the window' and 'send a space to the window'. </p>

<p>I can already do this locally, but only locally, with xdotools, LDTP2 and Sikuli. On Travis CI, however, I cannot get those tools to run successfully. I have been trying to write a <a href=""https://github.com/richelbilderbeek/testing_cpp_gui_applications_tutorial"" rel=""nofollow noreferrer"">tutorial</a> about it (<a href=""https://github.com/richelbilderbeek/testing_cpp_gui_applications_tutorial/tree/master/scripts"" rel=""nofollow noreferrer"">these are my scripts</a>), I have <a href=""https://github.com/travis-ci/travis-ci/issues/6006"" rel=""nofollow noreferrer"">contacted the folks at Travis</a> and even <a href=""https://github.com/richelbilderbeek/testing_cpp_gui_applications_tutorial/issues/3"" rel=""nofollow noreferrer"">set a bounty here</a>, all without success.</p>

<p>Because this is a complex process (setting up a windows manager on Travis, writing desktop applications to test, writing scripts to test these in bash) I think it is not useful to post those little individuals errors here (most have answers here already). </p>

<p><strong>My question is</strong>: does anyone have a working example of</p>

<ul>
<li>a non-web C++ GUI application</li>
<li>that has its GUI tested both locally and on Travis</li>
<li>these tests consist out of sending key presses and mouse clicks</li>
</ul>

<p>I do not care about the exact tools (xdotools or some other window manager tool, Qt or some other C++ GUI library, bash or any other scripting language). All I want is to have Travis CI check my GUI upon a <code>git push</code>.</p>
",https://stackoverflow.com/questions/42595612/c-desktop-gui-testing-on-travis-ci,"['c++', 'user-interface', 'travis-ci', 'desktop-application', 'xdotool']",689,FALSE,2,2
