title,body,link,tags,view_count,is_answered,score,answer_count
Database Testing Automation using Java - Trigger ETL JoB,"<p>I have written tests in Java to validate data from database based on some event took place in an application, As soon as that event happens it updates and adds few records in database.</p>

<p><strong><em>Ex:</em></strong> </p>

<p><strong>Table Name</strong>: RecordsStatus</p>

<p><strong>Column Name</strong>: Status -> Flag 0 or 1</p>

<p>If this is 1 we have to run an ETL Job and have to verify some other tables that are updated based on ETL job, so there are 3 stages here that are to be tested</p>

<p>Some Action happens in an Application (<strong>No need to Test this</strong>)</p>

<ol>
<li>Flag is updated in database table</li>
<li>Run ETL Job</li>
<li>Verify data that is updated</li>
</ol>

<p>The entire process has to be in one single test as the unique id has to be used in all the 3 stages for validating the data.</p>

<p>I am thinking to write a listener in Java that checks for Flag from ""RecordStatus"" table based on which the ETL job has to run</p>

<p>Is this a good approach?, please suggest if there are any better approaches</p>

<p>Are there any open source tools to do similar testing</p>
",https://stackoverflow.com/questions/58737012/database-testing-automation-using-java-trigger-etl-job,"['java', 'database', 'testing', 'automation', 'etl']",133,False,1,0
How we can implement Cucumber test for database testing,"<p>I am trying to configure Cucumber test for database testing since my application have some rest services and I need to check the database in order to verify the records are updated with proper value.</p>

<p>I am using Postgres database. I have a feature file listed as below:</p>

<pre><code>Feature: API Test

Background: Given I am connected with the database

Scenario: I want to test the database connection        
When I run the select query         
Then I should see the result as ""Pranjal""
</code></pre>

<p>Database Connection class is as follows:</p>

<p>public class DatabaseConnection {</p>

<pre><code>public DatabaseConnection createConnection() throws Exception {

    try {
        //Connection URL Syntax: ""jdbc:postgresql://ipaddress:portnumber/db_name""       
        String dbUrl = ""jdbc:postgresql://localhost:5432/test"";                 

        //Database User name
        String username = ""postgres"";   

        //Database Password
        String password = ""12345678"";

        //Query to Execute      
        String query = ""select * from test where no = 1;"";

        //Load PostgreSQL JDBC driver       
        Class.forName(""org.postgresql.Driver"");         

        //Create Connection to DB       
        Connection con = DriverManager.getConnection(dbUrl,username,password);

        //Create Statement Object       
        Statement stmt = con.createStatement();                 

        // Execute the SQL Query. Store results in ResultSet        
        ResultSet rs = stmt.executeQuery(query);                            

        // While Loop to iterate through all data and print results     
        while (rs.next()){
            String myName = rs.getString(1);                                                                                           
            System.out.println(myName);     
        }       

        // closing DB Connection        
        con.close();
    } catch(SQLException e) {
      e.printStackTrace();
    }

    return new DatabaseConnection();            
}
</code></pre>

<p>}</p>

<p>I have a Runner Class which will going to execute my feature file.</p>

<p>I want my steps to execute the query and database connection is created as a Background condition..</p>

<p>Is there a way to achieve this?</p>
",https://stackoverflow.com/questions/54770304/how-we-can-implement-cucumber-test-for-database-testing,"['java', 'cucumber', 'database-testing']",17216,True,1,1
H2 database testing with mocked service gives nullpointer exception,"<p>I am working on a Spring Java-based project.
For testing purposes I have implemented a H2 in-memory DB, which has been filled with data via an xml doc.
I whish to test a method which updates database records via an incoming datagram.
First of all, this method check if there are any relevant data in the datagram arrived which are found in the database(here is a repository call), then calls for another external service with the given ids, which provides the actual data which needs to be placed into the DB instead of the already saved ones.
So, there is a repository call first, then a second call for an external service.
When I wish to test this function, I am using following annotations:</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@DatabaseSetup(""classpath:datasets/FileWhichContainsDbRecords.xml"")
</code></pre>

<p>Then I mock the external service with:</p>

<pre><code>@MockBean
private ServiceName myService;
</code></pre>

<p>And call the Spring repository with:</p>

<pre><code>@Autowired
private RepositoryName repositoryName;
</code></pre>

<p>And have the following test code:</p>

<pre><code>@Test
@Transactional
public void testCase() {
    GivenDg dg = Factory.createDg(""id1"", Collections.singletonList(Factory.createAnotherObject(""id2"", OPERATION_TYPE_MODIFY, Collections.singletonList(""channel""))));

    MyObject myObjectSavedInDB = repositoryName.findByProvidedIds(""id1"", ""id2"").get();

    when(serviceName.getData(anyString(), anyString(), anyString(), any())).thenReturn(
            Factory.createActualData(false, false, false, ""HUF"", Collections.singletonList(""channels"")));

    myService.updateFunction(dg);

    Optional&lt;MyObject&gt; optResult = repositoryName.findByProvidedIds(""id1"", ""id2"");
    assertTrue(optResult.isPresent());
    assertNotSame(optResult.get().isA(), myObjectSavedInDB.isA());
}
</code></pre>

<p>So, I which to mock the ServiceName service, and I have provided the response which I wish to have when this function is called but I keep getting NullPointer exception due to ServiceName is null.
It does not even get mocked.</p>

<p>Is it not possible to test repository and mock a service in the same time?
What am I doing wrong?</p>

<p>I would really appreciate any help!</p>

<p>Thank you!</p>

<hr>

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

<hr>

<pre><code>java.lang.NullPointerException
at ---------)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code></pre>

<hr>

<p>Ok, I found what was missing... Originally, I had the following annotations on my Test class:</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest()
@DatabaseSetup(""classpath:datasets/FileWhichContainsDbRecords.xml.xml"")
@ContextConfiguration(classes = {TestRepositoryConfig.class})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class})
@DirtiesContext()
@Transactional
</code></pre>

<p>I had to add <strong>MockitoTestExecutionListener.class</strong> to the list of TestExecutionListeners.... </p>
",https://stackoverflow.com/questions/54889355/h2-database-testing-with-mocked-service-gives-nullpointer-exception,"['java', 'spring', 'mockito', 'h2', 'springrunner']",947,True,0,1
Problems with unit testing fire base storage,"<p>I need to write unit tests for my new function that connects to firebase storage. However i cannot find any documentation anywhere online for how to even mock the database.</p>

<p>Does this work the same way that realtime database testing works?</p>

<p>is it similar to: <code>var MockFirebase = require(""firebase-mock"").MockFirebase;</code></p>

<p>i need to be able to mock the storage bucket of the database, any help will be appreciated.</p>
",https://stackoverflow.com/questions/55593115/problems-with-unit-testing-fire-base-storage,"['angularjs', 'unit-testing', 'jasmine', 'firebase-storage']",227,False,3,0
Getting error while using generic generator,"<p>Using Spring Boot 2.1.1 with H2 database testing JPA.</p>

<p>Error </p>

<p><strong>There was an unexpected error (type=Internal Server Error, status=500).
Could not set field value [ST30790] value by reflection : [class com.example.demo.model.Student.id] setter of com.example.demo.model.Student.id; nested exception is org.hibernate.PropertyAccessException: Could not set field value [ST30790] value by reflection : [class com.example.demo.model.Student.id] setter of com.example.demo.model.Student.id</strong></p>

<p>Student class</p>

<pre><code>package com.example.demo.model;

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue(generator = ""Student_id"")
    @GenericGenerator(name = ""Student_id"", strategy = ""com.example.demo.model.StudentGenerator"")
    private int id;
    private String email;
    private String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
</code></pre>

<p>My generator</p>

<pre><code>package com.example.demo.model;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.enhanced.SequenceStyleGenerator;

import java.io.Serializable;
import java.util.Random;

public class StudentGenerator extends SequenceStyleGenerator {

    private static final String STUDENT_ID_PREFIX = ""ST"";

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        return STUDENT_ID_PREFIX + String.valueOf(generateID());
    }

    public static char[] generateID() {

        //Creating object of Random class
        Random obj = new Random();

        char[] otp = new char[5];

        for (int i = 0; i &lt; 5; i++) {
            otp[i] = (char) (obj.nextInt(10) + 48);
        }
        System.out.print(""Your OTP is : "" + otp.toString());
        return otp;
    }
}
</code></pre>

<p>Please help</p>
",https://stackoverflow.com/questions/58993656/getting-error-while-using-generic-generator,"['hibernate', 'spring-boot', 'jpa', 'h2']",1319,True,0,1
How we can implement Cucumber test for database testing,"<p>I am trying to configure Cucumber test for database testing since my application have some rest services and I need to check the database in order to verify the records are updated with proper value.</p>

<p>I am using Postgres database. I have a feature file listed as below:</p>

<pre><code>Feature: API Test

Background: Given I am connected with the database

Scenario: I want to test the database connection        
When I run the select query         
Then I should see the result as ""Pranjal""
</code></pre>

<p>Database Connection class is as follows:</p>

<p>public class DatabaseConnection {</p>

<pre><code>public DatabaseConnection createConnection() throws Exception {

    try {
        //Connection URL Syntax: ""jdbc:postgresql://ipaddress:portnumber/db_name""       
        String dbUrl = ""jdbc:postgresql://localhost:5432/test"";                 

        //Database User name
        String username = ""postgres"";   

        //Database Password
        String password = ""12345678"";

        //Query to Execute      
        String query = ""select * from test where no = 1;"";

        //Load PostgreSQL JDBC driver       
        Class.forName(""org.postgresql.Driver"");         

        //Create Connection to DB       
        Connection con = DriverManager.getConnection(dbUrl,username,password);

        //Create Statement Object       
        Statement stmt = con.createStatement();                 

        // Execute the SQL Query. Store results in ResultSet        
        ResultSet rs = stmt.executeQuery(query);                            

        // While Loop to iterate through all data and print results     
        while (rs.next()){
            String myName = rs.getString(1);                                                                                           
            System.out.println(myName);     
        }       

        // closing DB Connection        
        con.close();
    } catch(SQLException e) {
      e.printStackTrace();
    }

    return new DatabaseConnection();            
}
</code></pre>

<p>}</p>

<p>I have a Runner Class which will going to execute my feature file.</p>

<p>I want my steps to execute the query and database connection is created as a Background condition..</p>

<p>Is there a way to achieve this?</p>
",https://stackoverflow.com/questions/54770304/how-we-can-implement-cucumber-test-for-database-testing,"['java', 'cucumber', 'database-testing']",17216,True,1,1
How can I run integration tests without modifying the database?,"<p>I am making some integration tests for an app, testing routes that modify the database. So far, I have added some code to my tests to delete all the changes I have made to the DB because I don't want to change it, but it adds a lot of work and doesn't sounds right. I then thought about copying the database, testing, deleting the database in my testing script. The problem with that is that it is too long to do. Is there a method for doing that ? </p>
",https://stackoverflow.com/questions/58221583/how-can-i-run-integration-tests-without-modifying-the-database,"['unit-testing', 'testing', 'mocha.js', 'tdd', 'integration-testing']",713,True,0,2
Alternative to the now-abandoned dbunit extension?,"<p>So I can test code that uses a database using PHPUnit, I just installed the <a href=""https://github.com/sebastianbergmann/dbunit"" rel=""noreferrer"">DbUnit extension</a> using Composer, and I get the following message:</p>

<blockquote>
  <p>Package phpunit/dbunit is abandoned, you should avoid using it. No
  replacement was suggested.</p>
</blockquote>

<p>I've seen <a href=""https://github.com/sebastianbergmann/dbunit/issues/217"" rel=""noreferrer"">the issue on the extension being abandoned</a>, and people talk of rolling your own database testing code, but they don't go into any more details. Is there a recommended way to test database code using PHPUnit, or does anyone know of any examples?</p>

<p>(I did open <a href=""https://github.com/sebastianbergmann/phpunit/issues/3477"" rel=""noreferrer"">an issue</a> and asked the author of PHPUnit this, but his reply was quick and to the point - ""No, there is not."") :-/</p>
",https://stackoverflow.com/questions/54178160/alternative-to-the-now-abandoned-dbunit-extension,"['unit-testing', 'phpunit', 'dbunit']",1343,False,6,0
How can test a function that gets data from DB in a Laravel 5 package?,"<p>I'm working on a Laravel 5 package, and writing tests I'm trying to test a function that gets datas from DB.</p>

<pre><code>public function getPhotoDatasFromDb()
{
    $ret = GalleryImage::get()-&gt;keyBy('file_name');
    return $ret;
}
</code></pre>

<p>The returned values should be in this format:</p>

<pre><code>Collection {#416 ▼
  #items: array:2 [▼
    ""IMG_1979.jpg"" =&gt; GalleryImage {#423 ▼}
        ""alt_text"" =&gt; ""example alt text""
        ""description"" =&gt; ""lorem ipsum""
    ""IMG_1980.jpg"" =&gt; GalleryImage {#424 ▶}
  ]
}
</code></pre>

<p>I had already experiences with testing database testing in other Laravel applications.  </p>

<p><strong>My question is:</strong> since I'm writing a package, and in the dev environment I don't have an instance of the DB I'm wondering what is the best approach to test it?</p>

<p>If can help to have a wider picture, the database table gets created in the application trough this migration:</p>

<pre><code>&lt;?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateGalleryImagesTable extends Migration
{
    public function up()
    {
        Schema::create('gallery_images', function (Blueprint $table) {
            $table-&gt;increments('id');
            $table-&gt;string('file_name')-&gt;unique();
            $table-&gt;text('description')-&gt;nullable();
            $table-&gt;string('alt')-&gt;nullable();
            $table-&gt;string('video_link')-&gt;nullable();
            $table-&gt;timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('gallery_images');
    }
}
</code></pre>

<p>And this is the model associated</p>

<pre><code>&lt;?php

namespace DavideCasiraghi\ResponsiveGallery;

use Illuminate\Database\Eloquent\Model;

class GalleryImage extends Model
{
    protected $fillable = [
        'file_name', 'description', 'alt', 'video_link',
    ];
}
</code></pre>
",https://stackoverflow.com/questions/55207762/how-can-test-a-function-that-gets-data-from-db-in-a-laravel-5-package,"['laravel', 'unit-testing', 'laravel-5', 'phpunit']",527,True,1,1
Restoring sharded Mongodb does not include information on shards,"<p>I am using mongodump and mongorestore for taking the backup and recovering the MongoDB sharded cluster 3.2. ( 3 node cluster)</p>

<p>I have created a database called ""testing"" which has a collection named ""collection1"" and ""collection2"" 
I have then enabled sharding on the ""testing"" database and sharded the collections ""collection1"" and ""collection2"".</p>

<p>I then tried taking the backup using 
mongodump -d testing --out /backups/shard
Backup worked fine.</p>

<p>Next, I have dropped the database ""testing""</p>

<p>Now I tried to restore it back using mongorestore.
mongorestore -d ""testing"" /backups/shard/testing/
Restored completed.</p>

<p>Although the database and its collections were restored. I see that sharding is not enabled in the restored database.
How to retain the sharded information of a particular database so that after the restore operation, the collection should be in the same sharded state.</p>
",https://stackoverflow.com/questions/58412722/restoring-sharded-mongodb-does-not-include-information-on-shards,"['mongodb', 'sharding', 'mongodump', 'mongorestore']",106,False,1,0
Test configuration for Jpa auditing,"<p>I am trying to use Spring Data, Hibernate Envers and auditing in Spring Boot application. I have configured AuditorAwareImpl</p>

<pre><code>public class AuditorAwareImpl implements AuditorAware&lt;String&gt; {

    @Override
    public Optional&lt;String&gt; getCurrentAuditor() {
        return Optional.of(""Default auditor"");
    }
}
</code></pre>

<p>and configuration class for it.</p>

<pre><code>@Configuration
@EnableJpaAuditing(auditorAwareRef = ""auditorProvider"")
public class AuditingConfiguration {

    @Bean
    public AuditorAware&lt;String&gt; auditorProvider() {
        return new AuditorAwareImpl();
    }
}
</code></pre>

<p>Now I would like to create AuditorAware for my Integration tests. I have created new configuration class with test auditor</p>

<pre><code>@Configuration
@Profile(""test"")
@EnableJpaAuditing(auditorAwareRef = ""testAuditorProvider"")
public class TestAuditingConfiguration {

    @Bean
    @Primary
    public AuditorAware&lt;String&gt; testAuditorProvider() {
        return () -&gt; Optional.of(""Test auditor"");
    }

}
</code></pre>

<p>And when I try to write my integration test like this</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(""test"")
public class AuditingApplicationTests {

    @Autowired
    private AuditorAware&lt;String&gt; auditorAware;

    @Autowired
    private MovieRepository movieRepository;

    @Test
    public void testCurrentAuditor() {
        String currentAuditor = auditorAware.getCurrentAuditor().get();
        assertEquals(""Test auditor"", currentAuditor);
    }

    @Test
    public void movieRepositoryTest() {
        Movie movie = new Movie(""Movie"");
        movieRepository.save(movie);

        List&lt;Movie&gt; movies = movieRepository.findAll();
        Movie result = movies.get(0);
        assertEquals(""Test auditor"", result.getCreatedBy());
    }
}
</code></pre>

<p>I am getting this error:</p>

<pre><code>Caused by: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'jpaAuditingHandler' defined in null: Cannot register bean definition [Root bean: class [org.springframework.data.auditing.AuditingHandler]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] for bean 'jpaAuditingHandler': There is already [Root bean: class [org.springframework.data.auditing.AuditingHandler]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] bound.
</code></pre>

<p>When I remove <code>@EnableJpaAuditing</code> from <code>TestAuditingConfiguration</code> it works fine with one exception - autowired <code>auditorAware</code> in test is one from <code>TestAuditingConfiguration</code> but on the other hand for auditing is used from <code>AuditingConfiguration</code> so <code>result.getCreatedBy()</code> will return <code>Default auditor</code> instead of <code>Test auditor</code>. I read that for database integration tests should be used <code>@DataJpaTest</code> annotation so I have changed it. Now with enabled <code>@EnableJpaAuditing</code> on <code>TestAuditingConfiguration</code> I received:</p>

<pre><code>org.springframework.beans.factory.UnsatisfiedDependencyException:  Unsatisfied dependency expressed through field 'auditorAware'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.domain.AuditorAware&lt;java.lang.String&gt;' available: expected at least 1 bean which qualifies as autowire candidate
</code></pre>

<p>But after adding <code>@Import(TestAuditingConfiguration.class)</code> it works as I excpected - <code>result.getCreatedBy()</code> returns <code>Test auditor</code>. So finally my test class looks like:</p>

<pre><code>@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles(""test"")
@Import(TestAuditingConfiguration.class)
public class AuditingApplicationTests {

    @Autowired
    private AuditorAware&lt;String&gt; auditorAware;

    @Autowired
    private MovieRepository movieRepository;

    @Test
    public void testCurrentAuditor() {
        String currentAuditor = auditorAware.getCurrentAuditor().get();
        assertEquals(""Test auditor"", currentAuditor);
    }

    @Test
    public void movieRepositoryTest() {
        Movie movie = new Movie(""Movie"");
        movieRepository.save(movie);

        List&lt;Movie&gt; movies = movieRepository.findAll();
        Movie result = movies.get(0);
        assertEquals(""Test auditor"", result.getCreatedBy());
    }

}
</code></pre>

<p>Now I am really confused how beans are used in specific profiles and how <code>@SpringBootTest</code> and <code>@DataJpaTest</code> works. And why <code>@Import</code> was important for <code>@DataJpaTest</code>? Can anyone explain me that and what is preferred approach for database testing?</p>
",https://stackoverflow.com/questions/56317358/test-configuration-for-jpa-auditing,"['java', 'spring', 'spring-boot', 'spring-data-jpa', 'spring-test']",8118,True,13,2
testing.postgresql command not found: initdb inside docker,"<p>Hi i'm trying to make a unittest with postgresql database that use sqlalchemy and alembic</p>

<p>Also im running it on docker postgresql</p>

<p>I'm following the docs of testing.postgresql(<a href=""https://pypi.org/project/testing.postgresql/"" rel=""noreferrer"">docs</a>) to set up a temporary postgresql instance handle database testing and wrote the the following test:</p>

<pre><code>def test_crawl_bds_obj(self):
    with testing.postgresql.Postgresql() as postgresql:
        engine.create_engine(postgresql.url())
        result = crawl_bds_obj(1 ,'/ban-can-ho-chung-cu-duong-mai-chi-tho-phuong-an-phu-prj-the-sun-avenue/nh-chu-gap-mat-tien-t-q2-thuoc-du-tphcm-pr22171626')
        self.assertEqual(result, 'sell')
</code></pre>

<p>The crawl_bds_obj() basically save information from an URL and save it to the database using session.commit() and return the type data</p>

<p>When i tried to run the test it return the following error:</p>

<pre><code>ERROR: test_crawl_bds_obj (tests.test_utils.TestUtils)
raise RuntimeError(""command not found: %s"" % name)
RuntimeError: command not found: initdb
</code></pre>

<p>In the docs it said that ""testing.postgresql.Postgresql executes initdb and postgres on instantiation. On deleting Postgresql object, it terminates PostgreSQL instance and removes temporary directory.""</p>

<p>So why am i getting initdb error when i already installed testing.postgresql and had postgresql running on my docker?</p>

<p><strong>EDIT:</strong></p>

<p>I aslo had set my data path but it still return the same error</p>

<p>dockerfile:</p>

<pre><code>FROM python:slim-jessie
ADD requirements.txt /app/requirements.txt
ADD . /app/
WORKDIR /app/
RUN pip install -r requirements.txt
</code></pre>

<p>docker-compose:</p>

<pre><code>  postgres:
    image: postgres
    restart: always
    environment:
      - POSTGRES_USER=${POSTGRES_DEFAULT_USER}
      - POSTGRES_PASSWORD=${POSTGRES_DEFAULT_PASSWORD}
      - POSTGRES_DB=${POSTGRES_DEFAULT_DB}
      - POSTGRES_PORT=${POSTGRES_DEFAULT_PORT}
    volumes:
      - ./data/postgres:/var/lib/postgresql/data
  pgadmin:
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
    volumes:
       - ./data/pgadmin:/root/.pgadmin
    ports:
      - ""${PGADMIN_PORT}:80""
    logging:
      driver: none
    restart: unless-stopped

  worker:
    build:
      context: .
      dockerfile: Dockerfile
    command: ""watchmedo auto-restart --recursive -p '*.py'""
    environment:
      - C_FORCE_ROOT=1
    volumes:
      - .:/app
    links:
      - rabbit
    depends_on:
      - rabbit
      - postgres
</code></pre>

<blockquote>
  <p>testing.postgresql.Postgresql(copy_data_from='data/postgres:/var/lib/postgresql/data')</p>
</blockquote>
",https://stackoverflow.com/questions/57720546/testing-postgresql-command-not-found-initdb-inside-docker,"['python', 'postgresql', 'docker', 'sqlalchemy', 'python-unittest']",3522,True,6,1
Larravel project has no migration scripts for the database. Does the `Illuminate\Foundation\Testing\RefreshDatabase` handles that and how?,"<p>I inherited a laravel project to maintain and for various unexplained to me reasons (previous devs are gone, without any way to contact them) has no database migrations for it.</p>

<p>In my code base, I have been tasked to increase the code coverage for the tests. But the tests between them have no isolation whatsoever, therefore in contrary with this [answer][1], some of them may fail due to this reason.</p>

<p>In order to fix this problem I found this [solution][2] provided from laravel itself:</p>

<pre><code>namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        // Test something here
    }
}
</code></pre>

<p>But in my rationale there is the following thorn:</p>

<p>Does this approach work without migration scripts, if no how I can overcome the problem?</p>

<p>And for that, I want your contribution in order to remove it.</p>

<p>[1] <a href=""https://softwareengineering.stackexchange.com/a/394148/249660"">https://softwareengineering.stackexchange.com/a/394148/249660</a></p>

<p>[2] <a href=""https://laravel.com/docs/5.8/database-testing#resetting-the-database-after-each-test"" rel=""nofollow noreferrer"">https://laravel.com/docs/5.8/database-testing#resetting-the-database-after-each-test</a></p>
",https://stackoverflow.com/questions/56865705/larravel-project-has-no-migration-scripts-for-the-database-does-the-illuminate,"['database', 'laravel', 'phpunit']",44,False,1,1
Vagrant + PHPUnit performance on PC too slow compared to Mac,"<p>I recently added a pretty big PHPUnit test suite to a LAMP application in a vagrant box on PC. </p>

<p>The test suite involves setting up/tearing down the seed database before every test from an XML seed, as per PHPUnit's documentation. <a href=""https://phpunit.de/manual/6.5/en/database.html"" rel=""nofollow noreferrer"">see PHPUnit database testing.</a></p>

<p>I noticed that the same test suite runs more than 10 times faster using the same vagrant box but on Mac. Same with CI (CircleCI), the suite runs amazingly fast there.</p>

<p>I did some investigation and it seems that the slow part is - unsurprisingly - the <code>getDataSet</code> step which loads the fixtures.</p>

<p>The suite takes about 2 minutes to run on PC, and less than 20 seconds on Mac. That is surprising to me. </p>

<p>Anybody knows why there's such a drastic difference in performance between Mac and PC running the same Vagrant box and test suite?</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/55110026/vagrant-phpunit-performance-on-pc-too-slow-compared-to-mac,['vagrant'],77,False,0,0
Why are we forced to use keepSynced with firebase database?,"<p>I am using react native with Firebase Realtime Database. Testing a simple chat app and I am fetching the chats like so:</p>

<pre><code> this.friendChatRef = this.db.ref('messages/' + this.chat_id + '/' + this.friend_id)

 const friendChatRef = this.friendChatRef.limitToLast(9)

 const fcrp = friendChatRef.once('value')
</code></pre>

<p>The goal is to always get the last 9 messages from the conversation when the component/view mounts. </p>

<p>The problem is that It will fetch 9 chats but they are not the latest in any way. I can add 10+ new messages but they will never be fetched until I add this:</p>

<pre><code> friendChatRef.keepSynced(true)
</code></pre>

<p>Then every time I access the chat it will fetch the latest 9 messages. </p>

<p>Why do we have to use keepSynched? I thought persistence is just for the offline data caching but it always checks if the cached data is outdated or not every time you create a ref and fetch the data?</p>

<p>Is there any way to keep the persistence and not use keepSynched to get the latest data?</p>
",https://stackoverflow.com/questions/56636798/why-are-we-forced-to-use-keepsynced-with-firebase-database,"['javascript', 'react-native', 'firebase-realtime-database']",53,False,0,0
When is Azure SQL ready to receive queries?,"<h2>Problem</h2>

<p>When I deploy an Azure SQL Database, I would like to make some queries immediately after (on the Azure DevOps agents). Is there any way to find out when it is ready to receive queries?</p>

<h2>Testing if the server is ""Ready""</h2>

<p>I have tried ensuring that the server is running before calling the database:</p>

<pre><code># Looping till server is ready
status=""Not Ready""
time=0
while [ ""$status"" != ""Ready"" ]
do   
   state=$(az sql server show --resource-group $resourcegroup --name $servername --query state -o tsv)
   echo ""Current state is $state""
   sleep 1m
   echo ""Have been waiting $time minutes""
   time=$((time + 1))
done
</code></pre>

<h2>Testing if database is ""Online""</h2>

<p>As this didn't do the trick, I decided to write my ""wait"" statement at the database level, and to ensure that it is online before I make queries.</p>

<pre><code># Looping till database is online
status=""Offline""
time=0
while [ ""$status"" != ""Online"" ]
do   
   status=$(az sql db show --resource-group $resourcegroup --server $servername --name $databasename --query status -o tsv)
   echo ""Current status is $status""
   sleep 1m
   echo ""Have been waiting $time minutes""
   time=$((time + 1))
done
</code></pre>

<p>This also does not work, and I get an error when I make my first call using sqlcmd. However, if I wait like 5-10 minutes and run the same calls on a new agent the calls go through.</p>

<pre><code>sqlcmd -U $databaseuser -P $databasepw -S $databasehost -d $databasename -Q ""CREATE USER $databaseuser2 FROM LOGIN $databaseuser2""
</code></pre>

<p>Example of the ERRORs:</p>

<pre><code>2019-09-11T08:54:19.6306534Z Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout expired.
2019-09-11T08:54:19.6306875Z Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : TCP Provider: Error code 0x2AF9.
2019-09-11T08:54:19.6308179Z Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online..
</code></pre>

<h2>What else should be checked?</h2>

<p>I looked at the <a href=""https://dba.stackexchange.com/questions/198898/when-is-the-sql-server-database-ready-to-accept-queries"">following post</a>, but it requires that the database actually accepts queries to be carried out. </p>
",https://stackoverflow.com/questions/57884158/when-is-azure-sql-ready-to-receive-queries,"['bash', 'azure-sql-database', 'status', 'sqlcmd', 'azure-cli']",184,True,0,1
