title,body,link,tags,view_count,is_answered,score,answer_count
JUnit Integration Testing NamedJdbcTemplate,"<p>I have a Repository class RaRepository as below</p>
<pre><code>@Repository
public class RaRepository{
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;

public List&lt;raAttribute&gt; findFieldsByItemId(list&lt;string&gt; itemsId){
String sql = &quot;select * from abc where id in (:itemsId)&quot;;
SqlParameterSource param = new MapSqlParameterSource(&quot;itemsId&quot;,itemsId);
List&lt;raAtrribute&gt; raAttList = jdbcTemplate.query(sql, param, 
(rs, rowNum) -&gt; new raAtrribute(rs.getString(ps_name)));

return raAttList;
}

}
</code></pre>
<p>I have written a Junit Test class as below</p>
<pre><code>public class RaRepositoryTest {
@Autowired 
Private RaRepository raRepository;

@Test
public void findFieldsByItemId(){
List&lt;String&gt; itemsId = new ArrayList&lt;&gt;();
itemsId.add(&quot;VZ203&quot;)
List&lt;raAttribute&gt; raAttlist = raRepository.findFieldsByItemId(itemsId);
Assert.assertEquals(2, raAttlist.size);
}
</code></pre>
<p>The datasource written in application.properties file. I need to connect to actual db and run tests. I have tried with annotations like @RunWith(SpringRunner.class), @DataJdbcTest etc. I am new to jdbctemplate and not sure how to write test case for above scenario to achieve db connectivity.</p>
<p>Note: Iam using JUnit4 andService class which actually calls findFieldsByItemId method have separate mocking unit test.</p>
",https://stackoverflow.com/questions/75422504/junit-integration-testing-namedjdbctemplate,"['java', 'database', 'junit', 'mockito', 'namedparameterjdbctemplate']",31,False,0,0
Spring Boot Integration Testing with Plugins,"<p>I have a Spring Boot application that supports plugins. Plugins are jar files added to the core application docker container when deployed. The core application scans the plugin jars and adds components to the context.</p>
<p>I am looking for the best way to integration test the plugins with the core application. To that end, I added the core application jar as a test-scoped dependency for the plugins, but I'm not sure how run the tests with the full application context. I tried adding the primary configuration class from the core application to the @SpringBootTest annotation on the plugin tests, but I'm getting a cannot find symbol compilation error, so apparently that will not work with classes inside dependency jars.</p>
<pre><code>@CamelSpringBootTest
@SpringBootTest(
    classes = { CoreApplication.class },
    properties = { 
&quot;spring.cloud.consul.enabled=false&quot;,&quot;spring.cloud.consul.discovery.enabled=false&quot;} // disable 
consul to avoid errors
)
@EnableAutoConfiguration
@ActiveProfiles(&quot;test&quot;)
public class APluginTest {
</code></pre>
<p>Any suggestions on how I should wire these integration tests for plugins?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/76177079/spring-boot-integration-testing-with-plugins,"['java', 'spring-boot']",18,False,0,0
Integration testing FastAPI with user authentication,"<p>I am trying to write some integration tests for my FastAPI endpoints and am not sure what the best solution is to testing the endpoints that require a user to be logged in.</p>
<p>I am following the FastAPI authentication documentation for my auth flow which is just username password and then receiving a token.</p>
<p>How can I test endpoints using a logged in user?</p>
<p>Example endpoint to test:</p>
<pre><code>@app.get(&quot;/lists/{id}&quot;, response_model=ListDto)
async def get_list(
    id: int,
    current_user: User = Depends(get_current_active_user),
):
    usecase = GetList(list_id=id, current_user=current_user)
    list = usecase()
    if not llist:
        raise HTTPException(status_code=404, detail=f&quot;List with id:{id} not found&quot;)
    return list
</code></pre>
",https://stackoverflow.com/questions/75466872/integration-testing-fastapi-with-user-authentication,"['python', 'testing', 'integration-testing', 'fastapi']",550,True,0,1
Spring integration testing with mocked dependencies,"<p>I'm using Spring Boot. I have Service class (annotated <code>@Service</code>) with a method annotated with <code>@Retryable</code>.</p>
<p>For one of my integration test, I would like to load the Service bean to the context (with all of it's configurations and annotations).</p>
<p>The service has several dependencies. For example,</p>
<pre class=""lang-java prettyprint-override""><code>@Service
@EnableRetry
public class MyService{
    private final BeanOne beanOne;
    private final BeanTwo beanTwo;

    public MyService(BeanOne beanOne, BeanTwo beanTwo){
        this.beanOne = beanOne;
        this.beanTwo = beanTwo
    }
    
    @Retryable(value = RuntimeException.class , maxAttempts = 3)
    public void serviceAction(){
        beanOne.doSomething();
        beanTwo.doSomething();
        doMoreThings();
    }

    private void doMoreThings(){
        //things
        //eventually throws Runtime Exception

    }
}
</code></pre>
<p>I want to check that I indeed implemented everything regarding the retry correctly.</p>
<p>I'm trying to write a Spring integration test, when mocking the dependency beans, but still loading the MyService bean to the context (to check the retryable).</p>
<p>I tried mocking the dependency beans (using JUnit4 and Mockito):</p>
<pre class=""lang-java prettyprint-override""><code>@Import({MyService.class})
@RunWith(SpringRunner.class)
public class MyServiceIntegrationTest{
    @Autowired
    private MyService myService;
    
    @MockBean
    private BeanOne beanOne;

    @MockBean
    private BeanTwo beanTwo;

    @Test
    public void test(){
        myService.serviceAction();
        verify(beanTwo,times(3)).doSomething();
    }
}
</code></pre>
<p>However, I'm getting NullPointerException on the <code>beanOne.doSomething()</code> call. <strong>It seems like beanOne and beanTwo fields in <code>MyServiceIntegrationTest</code> class are indeed mocked, but are not autowired to the actual <code>myService</code>, and instead <code>myService</code>'s fields are null.</strong>
Note that the <code>@Retryable</code> annotation indeed works (and repeats 3 times), however this is since NullPointerException is a RuntimeException. The code never actually reaches the <code>doMoreThings()</code> method.</p>
",https://stackoverflow.com/questions/74987487/spring-integration-testing-with-mocked-dependencies,"['java', 'spring', 'spring-boot', 'mockito', 'junit4']",191,True,0,2
Backend integration testing sending firebase push notification,"<p>I have a dotnet application for sending push notifications using firebase where I store the user device token id and then send some notifications.
By default we write functional tests for all of our APIs to make sure everything is working together, however this is currently not possible for this api that sends the push notification because we don't have a valid token id during our tests.
That said, is there any way to generate a valid id token in the backend to use in these tests?</p>
",https://stackoverflow.com/questions/76228457/backend-integration-testing-sending-firebase-push-notification,"['.net', 'firebase', 'push-notification']",12,False,1,0
Parallel Integration testing with DBContext concurrent issue,"<p>I have integration tests having the base class which creates Docker Db container per test class:</p>
<pre><code>public class ApiFactory : WebApplicationFactory&lt;Program&gt;, IAsyncLifetime
{
    private readonly PostgreSqlContainer _postgreSqlContainer =
        new PostgreSqlBuilder().WithDatabase(&quot;Tests&quot;).Build();

    public Task InitializeAsync() =&gt; _postgreSqlContainer.StartAsync();
    Task IAsyncLifetime.DisposeAsync() =&gt; _postgreSqlContainer.DisposeAsync().AsTask();

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureTestServices(services =&gt;
        {
            services.AddTransient&lt;IEmailSender&gt;(_ =&gt; new StubEmailSender());
            services.SetDockerContainerDatabaseAsync(_postgreSqlContainer.GetConnectionString()).GetAwaiter().GetResult();
        });
    }
}

public static async Task SetDockerContainerDatabaseAsync(this IServiceCollection services, string connectionString)
{
    services.RemoveAll(typeof(DbContextOptions&lt;ApplicationDbContext&gt;));
    services.RemoveAll(typeof(DbContextOptions&lt;MessageDbContext&gt;));

    services.AddDbContextPool&lt;ApplicationDbContext&gt;(options =&gt;
        options.UseNpgsql(connectionString));
    services.AddDbContextPool&lt;MessageDbContext&gt;(options =&gt;
        options.UseNpgsql(connectionString));

    var serviceProvider = services.BuildServiceProvider();

    await serviceProvider.EnsureDbCreatedAsync&lt;ApplicationDbContext&gt;();
    await serviceProvider.EnsureDbMigratedAsync&lt;MessageDbContext&gt;();
}
</code></pre>
<p>And <code>BaseIntegrationTest</code> implementing the <code>ApiFactory</code>:</p>
<pre class=""lang-cs prettyprint-override""><code>public class BaseIntegrationTest : IClassFixture&lt;ApiFactory&gt;
{
    protected readonly ApiFactory _factory;
    public HttpClient ApiClient { get; set; }

    public BaseIntegrationTest(ApiFactory factory)
    {
        _factory = factory;
        ApiClient = _factory.CreateClient();
    }
}
</code></pre>
<p>Then integration test class which tests if <code>MessageService</code> sends an Email properly:</p>
<pre class=""lang-cs prettyprint-override""><code>public class MessageServiceTests : BaseIntegrationTest
{
    public MessageServiceTests(ApiFactory factory) : base(factory) { }

    [Fact]
    public async Task SendRegisterConfirmationEmail_Failed_InsertMessageQueue()
    {
        // Required Arranges...

        using var scope = _factory.Services.CreateScope();
        var messageQueueRepository = scope.ServiceProvider.GetRequiredService&lt;MessageQueueRepository&gt;();
        var messageService = new MessageService(emailSenderMock.Object, messageQueueRepository);

        // Sends an email and inserts message to the database via MessageQueueRepository
        await messageService.SendRegisterConfirmationEmailAsync(email, confirmationLink);

        //Verifies that event handler was called (which inserts data to database)
        emailSenderMock.Verify(e =&gt; e.SendAsync(email, RegisterConfirmation.SUBJECT, body), Times.Once);

        //Checks that message was inserted to the database
        var addedMessage = await messageQueueRepository.GetOneByCondition(m =&gt; m.To == email &amp;&amp; m.From == _senderEmail &amp;&amp; m.Status == MessageStatus.Failed).FirstOrDefaultAsync();

        Assert.NotNull(addedMessage);
    }
}
</code></pre>
<p>There is another test looking almost the same and also another test class (but for each test class there is a dedicated PostgreSQL database docker container) which also checks by using <code>MessageQueueRepository</code> and <code>MessageDbContext</code> if the entity was added to the table.</p>
<p>When I run those tests on my local machine everything is fine, but when I put it on CI under Ubuntu machine it gives me randomly:</p>
<blockquote>
<p>A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext</p>
</blockquote>
<p>or</p>
<blockquote>
<p>Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')</p>
</blockquote>
<p>And the line causing the issue is:</p>
<pre><code>var addedMessage = await messageQueueRepository.GetOneByCondition(m =&gt; m.To == email &amp;&amp; m.From == _senderEmail &amp;&amp; m.Status == MessageStatus.Failed).FirstOrDefaultAsync();
</code></pre>
<p>And I know, this is because I went into the case where those 3 tests were run on the same time and cause <code>MessageDbContext</code> to throw BUT question is, can I somehow handle dependency injection here to still run tests in parallel? Maybe I should create scope somehow differently, or there is no other way than making them run separate/sequential.</p>
<p><code>GetOneByCondition</code> code:</p>
<pre><code>public virtual IQueryable&lt;TDbModel&gt; GetOneByCondition(
    Expression&lt;Func&lt;TDbModel, bool&gt;&gt; conditionPredicate,
    bool tracking = false,
    params string[] includes)
{
    var queryableEntities = tracking ? GetDbSet() : GetDbSet().AsNoTracking();

    RepositoryHelper&lt;TDbModel&gt;.Include(ref queryableEntities, includes);
    RepositoryHelper&lt;TDbModel&gt;.ApplyCondition(ref queryableEntities, conditionPredicate);

    return queryableEntities;
}

public static void ApplyCondition(ref IQueryable&lt;TDbModel&gt; queryableEntities, Expression&lt;Func&lt;TDbModel, bool&gt;&gt;? conditionPredicate)
{
    if (conditionPredicate != null)
        queryableEntities = queryableEntities.Where(conditionPredicate);
}

public static void Include(ref IQueryable&lt;TDbModel&gt; queryableEntities, string[] includes)
{
    if (includes != null)
    {
        foreach (var include in includes.Where(x =&gt; !string.IsNullOrEmpty(x)))
        {
            queryableEntities = queryableEntities.Include(include);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/76181658/parallel-integration-testing-with-dbcontext-concurrent-issue,"['c#', 'integration-testing', 'xunit', 'dbcontext', 'testcontainers']",115,False,0,1
Dynamically reuse integration testing scenarios in pytest,"<p>I have a set of classes for which each property and method must be tested.</p>
<p>Something like</p>
<pre><code>datasets = [{
    &quot;klass&quot;: MyClass1,
    &quot;a&quot;: 1,
    &quot;c&quot;: 3,
},
{
    &quot;klass&quot;: MyClass2,
    &quot;a&quot;: 12,
    &quot;b&quot;: 13,
}]
</code></pre>
<p>Note that these are just quick examples, the test data is much more complex and large.</p>
<p>Coming from ruby and the Shoulda framework, before I actually discovered how unwieldy python testing was, I had thought I could simply write some dynamic generator that would allow me to do something like</p>
<pre><code># tests/test_datasets_client_1.py
for dataset in datasets_client_1:
    generate_test_case(**dataset)

# tests/test_datasets_client_2.py
for dataset in datasets_client_2:
    generate_test_case(**dataset)
</code></pre>
<p>Which would really be calling</p>
<pre><code># tests/test_libraries.py

def generate_test_case(**kwargs):
    # do some stuff to register TestCase(**kwargs) so that it's picked up by the testing framework
    # stuff like markers and the test name would also be dynamically set here based on the kwargs


class TestCaseDynamic:
    def __init__(klass, **kwargs):
        self.instance = klass(kwargs[&quot;some_specific_parameter&quot;]) 
        self.kwargs = kwargs # or setattr, doesn't matter as long as they're available in the rest of the instance methods
        
    def test_a(self):
        if self.kwargs[&quot;a&quot;]:
            assert self.instance.a == self.kwargs[&quot;a&quot;]
        
    def test_b(self):
        if self.kwargs[&quot;b&quot;]:
            assert self.instance.b &gt; self.kwargs[&quot;b&quot;]
        
    def test_c(self):
        if self.kwargs[&quot;c&quot;]:
            assert self.instance.c &lt;= self.kwargs[&quot;c&quot;]
        
</code></pre>
<p>However python testing is much worse than I anticipated, and there does not seem to be an immediate way to do this. Can anyone point me in the right direction? How can I dynamically generate a huge quantity of these tests without losing my sanity in the process?</p>
<p>How can I make this class instance actually be an instance with self persistence? <code>self.instance.b</code> and <code>self.instance.c</code> could be calling the same expensive method internally, which is cached between instances, so why would I have to wait 5 minutes for each of these tests when in the real world it would just be called once?</p>
<p>Given python's dynamicity I had thought these were all rethorical questions with easy answers, but after dipping my toes in pytest I am not so sure anymore.</p>
<p>Every single example code I've seen is overly complicated and relies on metaclasses, nested decorators and other hard to understand code that I have to sit down and study to achieve something that is basic, obvious behavior in other languages. I found some previous answers like <a href=""https://stackoverflow.com/a/35580034/7376511"">https://stackoverflow.com/a/35580034/7376511</a>, but there was no way to actually dynamically call that class with the dataset without redefining it in every test file, which defeats the aim of declaring the testing scenario once and importing it everywhere else.</p>
",https://stackoverflow.com/questions/75670679/dynamically-reuse-integration-testing-scenarios-in-pytest,"['python', 'testing', 'pytest', 'integration-testing']",111,False,0,1
Integration Testing ignored Type org.springframework.test.context.junit.jupiter.SpringExtension not present,"<p>I write integration tests for *Controller class. Here are the test class:
<a href=""https://i.stack.imgur.com/fzd2w.png"" rel=""nofollow noreferrer"">Test class</a></p>
<p>My script to db decribed in *.sql file. I will run this file before each test case.</p>
<p>I have the next error when trying to run my tests. <a href=""https://i.stack.imgur.com/TNv8f.png"" rel=""nofollow noreferrer"">Error</a></p>
<p>I have read about this mistake and I use correct annotation for test. But my test still ignored. I think that problem inside pom.xml but I dont know where.
Here are all dependencies which are related to tests
<a href=""https://i.stack.imgur.com/BPwLg.png"" rel=""nofollow noreferrer"">dependencies</a></p>
<p>I tried to use another dependencies but it doesn't work.</p>
",https://stackoverflow.com/questions/75897749/integration-testing-ignored-type-org-springframework-test-context-junit-jupiter,"['junit', 'controller', 'integration-testing', 'junit-jupiter']",41,False,0,0
Spring Boot: pruning application context for integration testing,"<p>JUnit Jupiter 5.7.2 and Spring Boot 2.6.3 here. I have the following service class:</p>
<pre><code>@Service
public class PasswordService implements PasswordEncoder {

    private BCryptPasswordEncoder passwordEncoder;
    private PasswordGenerator passwordGenerator;
    private CharacterCharacteristicsRule passwordCharacteristicsRule;
    private Integer minPasswordLength;

    @Autowired
    public PasswordService(
            BCryptPasswordEncoder passwordEncoder,
            PasswordGenerator passwordGenerator,
            CharacterCharacteristicsRule passwordCharacteristicsRule,
            @Value(&quot;${myapp.users.passwords.min-length}&quot;) Integer minPasswordLength) {
        this.passwordEncoder = passwordEncoder;
        this.passwordGenerator = passwordGenerator;
        this.passwordCharacteristicsRule = passwordCharacteristicsRule;
        this.minPasswordLength = minPasswordLength;
    }

    public String generatePassword() {
        return passwordGenerator.generatePassword(minPasswordLength, passwordCharacteristicsRule.getRules());
    }

    public String protectPassword(String plaintextPassword) {
        return passwordEncoder.encode(plaintextPassword);
    }

    @Override
    public String encode(CharSequence rawPassword) {
        return protectPassword(rawPassword.toString());
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return protectPassword(rawPassword.toString()).equals(encodedPassword);
    }

}
</code></pre>
<p>I have a unit test for each method, but because its <code>generatePassword()</code> method is so important and depends so heavily on its dependencies, I also want to create an integration test for it that actually autowires/injects it with <strong>real</strong> instances of all of its dependencies.</p>
<p>My best attempt:</p>
<pre><code>@SpringBootTest
public class PasswordServiceIT {

    @Inject
    private PasswordService passwordService;

    @Test
    public void when_generatePassword_should_generate_valid_password() {

        String password = passwordService.generatePassword();
        System.out.println(String.format(&quot;Password is: %s&quot;, password));

    }


}
</code></pre>
<p>When I run this test I am getting <code>Failed to load ApplicationContext</code> because, in my <code>application.yml</code>, I have the following:</p>
<pre><code>server:
  port: ${SERVER_PORT}
  error:
    whitelabel:
      enabled: false
</code></pre>
<p>And when the Application Context tries to spin up, it can't inject <code>${SERVER_PORT}</code> because thats typically set by environment variable.</p>
<p>I don't want to hardcode it or set a default in the YAML like <code>${SERVER_PORT:9200}</code>, etc. I just don't like hardcoding configs (especially in other places, like where credentials are stored) in these YAML files.</p>
<p>Is there a way to &quot;<em>prune</em>&quot; which parts of the application context get loaded? This entire &quot;Password Generation system&quot; doesn't need to talk to any databases, remote services, shouldn't need a server port to start from, etc.</p>
",https://stackoverflow.com/questions/75866252/spring-boot-pruning-application-context-for-integration-testing,"['spring-boot', 'junit', 'integration-testing']",16,True,1,1
should we bypass the authentication in integration testing,"<p>I am writing integration tests for my controllers..
Now, we have token validation enabled in our application (for azure). How should it be handled in integration test?</p>
<p>Is it good to get some mock token logic to generate a mock token with appropriate roles or should we use some test credentials for which we can get a real token and then use it for testing?</p>
",https://stackoverflow.com/questions/75194933/should-we-bypass-the-authentication-in-integration-testing,"['spring-boot', 'azure', 'mocking', 'integration-testing', 'access-token']",61,False,0,0
Spring Boot Integration Testing with TestContainers with MySql - BeanDefinitionStoreException,"<p>I'm trying to implement an integration test using TestContainers. But I'm continuously getting BeanDefinitionStoreException.</p>
<p>My Test Class</p>
<pre><code>    @SpringBootTest
@AutoConfigureMockMvc
class OrderServiceApplicationTests {

    @Container
    static final MySQLContainer mySQLContainer = new MySQLContainer&lt;&gt;(&quot;mysql:8.0.30&quot;)
            .withDatabaseName(&quot;testcontainer&quot;)
            .withUsername(&quot;test&quot;)
            .withPassword(&quot;test&quot;);

    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    OrderRepository orderRepository;

    @DynamicPropertySource
    static void setProperties(DynamicPropertyRegistry properties){
        properties.add(&quot;spring.datasource.url&quot;, mySQLContainer::getJdbcUrl);
        properties.add(&quot;spring.datasource.username&quot;, mySQLContainer::getUsername);
        properties.add(&quot;spring.datasource.password&quot;, mySQLContainer::getPassword);
    }

    @Test
    void shouldPlaceOrder() throws Exception {

        OrderItemsDto orderItemsDto = OrderItemsDto.builder()
                .skuCode(&quot;Test SKU&quot;)
                .price(new BigDecimal(123.32))
                .quantity(2).build();
        OrderDto orderDto = OrderDto.builder()
                .orderItemsDtos(Arrays.asList(orderItemsDto)).build();
        String reqString = objectMapper.writeValueAsString(orderDto);
        mockMvc.perform(MockMvcRequestBuilders.post(&quot;api/order&quot;)
        .contentType(MediaType.APPLICATION_JSON)
        .content(reqString))
                .andExpect(status().isCreated());
        Assertions.assertTrue(orderRepository.findAll().size() == 1);

    }

}
</code></pre>
<p>Here is my POM File</p>
<pre><code>    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;3.1.0-SNAPSHOT&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.example&lt;/groupId&gt;
    &lt;artifactId&gt;order-service&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;order-service&lt;/name&gt;
    &lt;description&gt;Order Service&lt;/description&gt;
    &lt;properties&gt;
        &lt;java.version&gt;17&lt;/java.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-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;com.mysql&lt;/groupId&gt;
            &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
            &lt;artifactId&gt;lombok&lt;/artifactId&gt;
            &lt;optional&gt;true&lt;/optional&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
            &lt;artifactId&gt;mysql&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter&lt;/artifactId&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.testcontainers&lt;/groupId&gt;
                &lt;artifactId&gt;testcontainers-bom&lt;/artifactId&gt;
                &lt;version&gt;1.18.0&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;

    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;excludes&gt;
                        &lt;exclude&gt;
                            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
                            &lt;artifactId&gt;lombok&lt;/artifactId&gt;
                        &lt;/exclude&gt;
                    &lt;/excludes&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
    &lt;repositories&gt;
        &lt;repository&gt;
            &lt;id&gt;spring-milestones&lt;/id&gt;
            &lt;name&gt;Spring Milestones&lt;/name&gt;
            &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/repository&gt;
        &lt;repository&gt;
            &lt;id&gt;spring-snapshots&lt;/id&gt;
            &lt;name&gt;Spring Snapshots&lt;/name&gt;
            &lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/releases&gt;
        &lt;/repository&gt;
    &lt;/repositories&gt;
    &lt;pluginRepositories&gt;
        &lt;pluginRepository&gt;
            &lt;id&gt;spring-milestones&lt;/id&gt;
            &lt;name&gt;Spring Milestones&lt;/name&gt;
            &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/pluginRepository&gt;
        &lt;pluginRepository&gt;
            &lt;id&gt;spring-snapshots&lt;/id&gt;
            &lt;name&gt;Spring Snapshots&lt;/name&gt;
            &lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/releases&gt;
        &lt;/pluginRepository&gt;
    &lt;/pluginRepositories&gt;

&lt;/project&gt;
</code></pre>
<p>This is my console.</p>
<pre><code>16:14:14.843 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.orderservice.OrderServiceApplicationTests]: OrderServiceApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
16:14:14.940 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration com.example.orderservice.OrderServiceApplication for test class com.example.orderservice.OrderServiceApplicationTests
16:14:15.163 [main] WARN org.testcontainers.utility.TestcontainersConfiguration -- Attempted to read Testcontainers configuration file at file:/C:/Users/binul/.testcontainers.properties but the file was not found. Exception message: FileNotFoundException: C:\Users\binul\.testcontainers.properties (The system cannot find the file specified)
16:14:15.169 [main] INFO org.testcontainers.utility.ImageNameSubstitutor -- Image name substitution will be performed by: DefaultImageNameSubstitutor (composite of 'ConfigurationFileImageNameSubstitutor' and 'PrefixingImageNameSubstitutor')

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v3.1.0-SNAPSHOT)

2023-05-10T16:14:15.441+05:30  INFO 13040 --- [           main] c.e.o.OrderServiceApplicationTests       : Starting OrderServiceApplicationTests using Java 17.0.7 with PID 13040 (started by binul in D:\Project Docs\R&amp;D\Microservices-Online-Shop\order-service)
2023-05-10T16:14:15.444+05:30  INFO 13040 --- [           main] c.e.o.OrderServiceApplicationTests       : No active profile set, falling back to 1 default profile: &quot;default&quot;
2023-05-10T16:14:16.013+05:30  INFO 13040 --- [           main] .t.d.DockerMachineClientProviderStrategy : docker-machine executable was not found on PATH ([C:\Program Files\Common Files\Oracle\Java\javapath, C:\Program Files (x86)\Common Files\Oracle\Java\javapath, C:\Windows\system32, C:\Windows, C:\Windows\System32\Wbem, C:\Windows\System32\WindowsPowerShell\v1.0\, C:\Windows\System32\OpenSSH\, C:\Program Files\Git\cmd, C:\Program Files\Java\jdk1.8.0_311\bin, C:\dev_tools\apache-maven-3.8.3\bin, C:\Program Files\PuTTY\, C:\Program Files\dotnet\, C:\Program Files\nodejs\, C:\Program Files\Meld\, C:\Users\binul\AppData\Local\Microsoft\WindowsApps, C:\Users\binul\AppData\Local\Programs\Microsoft VS Code\bin, C:\dev_tools\gradle-6.8.1\bin, C:\Users\binul\AppData\Roaming\npm, C:\Users\binul\.dotnet\tools])
2023-05-10T16:14:16.014+05:30 ERROR 13040 --- [           main] o.t.d.DockerClientProviderStrategy       : Could not find a valid Docker environment. Please check configuration. Attempted configurations were:
As no valid configuration was found, execution cannot continue.
See https://www.testcontainers.org/on_failure.html for more details.
2023-05-10T16:14:16.027+05:30  WARN 13040 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.example.orderservice.OrderServiceApplication]: Error processing condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration
2023-05-10T16:14:16.054+05:30  INFO 13040 --- [           main] .s.b.a.l.ConditionEvaluationReportLogger : 

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-05-10T16:14:16.088+05:30 ERROR 13040 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.example.orderservice.OrderServiceApplication]: Error processing condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:524) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.lambda$processGroupImports$1(ConfigurationClassParser.java:726) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.processGroupImports(ConfigurationClassParser.java:723) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorHandler.process(ConfigurationClassParser.java:694) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:182) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:415) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:287) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:344) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:115) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:747) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:565) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:733) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:435) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:58) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:46) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1405) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:545) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:184) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:118) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:191) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:130) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:241) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:377) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:382) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:377) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[na:na]
    at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310) ~[na:na]
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735) ~[na:na]
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) ~[na:na]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:376) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:289) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:288) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:278) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at java.base/java.util.Optional.orElseGet(Optional.java:364) ~[na:na]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:277) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:105) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:104) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:68) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) ~[na:na]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) ~[na:na]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69) ~[junit5-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) ~[junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) ~[junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) ~[junit-rt.jar:na]
Caused by: java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:60) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.processMemberClasses(ConfigurationClassParser.java:365) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:265) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:243) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:514) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    ... 93 common frames omitted
Caused by: java.lang.IllegalStateException: Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration
    at org.testcontainers.dockerclient.DockerClientProviderStrategy.getFirstValidStrategy(DockerClientProviderStrategy.java:212) ~[testcontainers-1.18.0.jar:1.18.0]
    at org.testcontainers.DockerClientFactory.getOrInitializeStrategy(DockerClientFactory.java:150) ~[testcontainers-1.18.0.jar:1.18.0]
    at org.testcontainers.DockerClientFactory.dockerHostIpAddress(DockerClientFactory.java:323) ~[testcontainers-1.18.0.jar:1.18.0]
    at org.testcontainers.containers.ContainerState.getHost(ContainerState.java:64) ~[testcontainers-1.18.0.jar:na]
    at org.testcontainers.containers.MySQLContainer.getJdbcUrl(MySQLContainer.java:104) ~[mysql-1.18.0.jar:na]
    at com.example.orderservice.OrderServiceApplicationTests.lambda$setProperties$0(OrderServiceApplicationTests.java:46) ~[test-classes/:na]
    at org.springframework.test.context.support.DynamicValuesPropertySource.getProperty(DynamicValuesPropertySource.java:43) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:85) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver$DefaultResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:123) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.findPropertyValue(ConfigurationPropertySourcesPropertyResolver.java:97) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:74) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:60) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:552) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseCondition.hasDataSourceUrlProperty(DataSourceAutoConfiguration.java:156) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseCondition.getMatchOutcome(DataSourceAutoConfiguration.java:139) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    ... 99 common frames omitted
</code></pre>
<p>I highly suspect that this is related to injecting Mysql image into the local environment.
Note : I did the same code to Mongodb and it works fine.</p>
<p>Could anyone had the same issue and resolved ? btw unit testing becoming embarrassing :-(</p>
",https://stackoverflow.com/questions/76217978/spring-boot-integration-testing-with-testcontainers-with-mysql-beandefinitions,"['java', 'spring-boot', 'unit-testing', 'testcontainers', 'testcontainers-junit5']",164,True,2,3
Separating Contexts of Spring Boot Applications for Integration Testing,"<p>I need to do integration testing on an ecosystem of spring boot based services. Most of these communicate with each other via REST APIs and use their own databases.
Besides, there is some additional stuff that needs to be done in the test cases: Setting up clients, posting and getting data through the services' APIs, etc.</p>
<p>Of course, I could straightforwardly boot all services as separate applications via Java's ProcessBuilder and pass test-specific configuration as arguments (as single properties or in terms of a test-specific <code>.yml</code>/<code>.properties</code> file). But I was wondering if it is not also possible to just launch all services inside the same process, e.g, via <code>SpringApplicationBuilder</code>.</p>
<p><strong>My central question: Is there any simple way to separate services' contexts from each other?</strong>
I am not familiar with boostrap contexts yet but to me it seems that these are not applicable to Spring Boot but Spring Cloud only?</p>
<p>We use maven, thus the integration test project's <code>pom.xml</code> has depedencies to all services' projects (where the respective <code>Application</code> classes are located in).</p>
<p>My sample test code looks like this:</p>
<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringJUnit4ClassRunner.class)
public class MyTest {

    @Test
    public void Test1() {
        SpringApplicationBuilder service1 = new SpringApplicationBuilder( my.service1.Application.class )
            .properties( &quot;spring.config.location=classpath:/service1.yml&quot; );
        service1.run();

        SpringApplicationBuilder service2 = new SpringApplicationBuilder( my.service2.Application.class )
            .properties( &quot;spring.config.location=classpath:/service2.yml&quot; );
        service2.run();

        // do test stuff...
    }
}
</code></pre>
<p>where each of the <code>Application</code> classes looks like</p>
<pre class=""lang-java prettyprint-override""><code>@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootApplication
@EnableConfigurationProperties
public class Application {
    public static void main( String [] args ) {
        TimeZone.setDefault( TimeZone.getTimeZone( &quot;UTC&quot; ) );
        SpringApplication.run( Application.class, args );
    }
}
</code></pre>
<p>Problem is now that the two services share the same Spring context. Omitting the <code>@RunWith(SpringJUnit4ClassRunner.class)</code> annotation does not change this.</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/75747246/separating-contexts-of-spring-boot-applications-for-integration-testing,"['spring-boot', 'integration-testing', 'spring-context']",46,False,1,0
End-To-End and Integration Testing with Dagger Hilt,"<p>My current test setup is using only End-To-End tests. So i do not Fake any network calls etc.</p>
<p>Since these tests are not reliable i tried to implement new tests using dagger hilt. In this case i replace my Repositories with Fake Repositories to test anything UI relevant. and in generall make my tests more fine grained.</p>
<p>Since dagger hilt allows me to replace modules in my androidTest folder with TestIntallIn it is easy for my new tests to change my real repositories with fake repos.</p>
<p>But if i still want to keep my End to End tests i did not find a solution so far to <strong>not</strong> replace the repos for them.</p>
<p>i have seen that i can uninstall modules per test class, but i think it is not a good idea to install and bind new dependencies for a large amount of integration tests just to keep my old end to end tests.</p>
<p>i tried to use seperate androidtest folders but did not succeed.
i also tried to make a seprate test module but same result.</p>
<p>so far i did not find a solution to make a general setup for my integration tests and end to end tests that are not replacing all necassary dependencies for each test class.</p>
<p>So is there a possiblity todo this? And in general what is a good approach to have ui tests that abstract away the repository and large integration test that work with a real repositroy but use e.g. MockWebServer?</p>
",https://stackoverflow.com/questions/75605567/end-to-end-and-integration-testing-with-dagger-hilt,"['android', 'dagger', 'dagger-hilt']",47,False,0,0
"Is this functinal testing, E2E testing, or Integration testing?","<p>What can we call the testing described below?
Integration testing, functional testing, or E2E testing?</p>
<p>It's a set of tests that call the server's APIs to simulate the user's workflow. This test uses real server components, such as running PostgreSQL, Redis, and ElasticSearch using Docker Compose. However, this test doesn't cover the client's behavior.</p>
<p>I've seen this kind of test many times, and some say it's functional testing, while others say it's E2E testing.</p>
<p>In the sense that it simulates the user's workflow, we can call it E2E testing. However, since it doesn't cover the client's (UI) behavior, some say it's not E2E testing.</p>
<p>So is it functional testing? But some say functional testing focuses on one product function. In that sense, it's not functional testing as it covers multiple product functions to follow the user's workflow.
Then, is the safest way to call this just integration testing?</p>
",https://stackoverflow.com/questions/76274380/is-this-functinal-testing-e2e-testing-or-integration-testing,['testing'],21,False,0,0
replacing bean in integration testing without overriding or using profiles,"<p>I'm writing integration tests and for some reason I need to replace on bean, which is completely unsound to be used in this testing. Bean overriding was disabled and I believe it was for good reason, so I don't accept enabling that as a solution. Another typical solution is to annotate the bean to be used in production with '!Test' profile and use tests with Test profile, which will make the conflict to go away. Doable solution, but since it expects us to know beforehand, which beans will might be needed to 'replace' in tests, I consider this just as a hack.</p>
<p>Can someone recommend a way, how to structure app, so that production code need not to care about its testing (I know, it cannot be 100% done, but laying out profiles like this, just to be able ...), need not to rely on bean overriding, but still be able to somehow replace certain bean in integration tests?</p>
",https://stackoverflow.com/questions/75803817/replacing-bean-in-integration-testing-without-overriding-or-using-profiles,['spring-boot'],17,False,0,0
Separate Program.cs to Startup.cs in ASP.NET WebAPI Minimal for Integration testing,"<p>I am trying to write integration tests for my web service.</p>
<p>I want to separate <code>Program.cs</code> into <code>Startup.cs</code> so test class can mock <code>TestStartup.cs</code>(or something like so). The point is swapping real services with mock services.</p>
<p>Attempt to use <code>Startup.cs</code> file for MinimalApi resulting <code>app</code> not compilable:</p>
<pre><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) {
    (...)
    // Error CS1929  'IApplicationBuilder' does not contain a definition for
    // 'MapGroup' and the best extension method overload 'EndpointRouteBuilderExtensions.MapGroup(IEndpointRouteBuilder, string)'
    // requires a receiver of type 'Microsoft.AspNetCore.Routing.IEndpointRouteBuilder'
    app.MapGroup(&quot;/product&quot;).MapProductApi().WithTags(&quot;Product&quot;);
    app.UseResponseCaching();
    app.UseOutputCache();
}
</code></pre>
<p>Am I going the right direction? Should Minimal Apis be used with <code>Startup.cs</code>?</p>
",https://stackoverflow.com/questions/75669331/separate-program-cs-to-startup-cs-in-asp-net-webapi-minimal-for-integration-test,"['c#', 'asp.net-web-api', 'integration-testing', 'minimal-apis']",180,True,2,1
Integration Testing Spring Data Envers using Testcontainers and Spring Boot DataJpaTest,"<p>I recently integrated Envers (Spring Data Envers) into my microservice and I'd like to test it.</p>
<p>I'm able to get my test to spin up a Testcontainer (Postgresql), run the Flyway migrations to create the tables, and do inserts into the tables using a JPA repository that I autowire.</p>
<p>But when I attempt to get the Revisions from the Envers audit table, I get an error stating that the table does not exist.</p>
<p>I suspect this has something to do with how I've configured this test using <code>@DataJpaTest</code>.  <code>@DataJpaTest</code> disables a lot of functionality that would otherwise be present with <code>@SpringBootTest</code>, so that only JPA-related code is wired up.  I'd like to add Envers to this.  It's not clear to me what I need to do to get the Envers code to run and create the <code>_aud</code> tables.</p>
<p>My test class (Groovy/Spock):</p>
<pre><code>@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles(&quot;tc&quot;)
class FooRepositoryITSpec extends Specification {

    @Autowired
    private FooRepository fooRepository

    void &quot;test envers functionality&quot;() {
        given:
        var foo = new Foo()

        when:
        fooRepository.save(foo)
        var revisions = fooRepository.findRevisions(foo.getId()) // ERROR HERE - org.postgresql.util.PSQLException: ERROR: relation &quot;foo_aud&quot; does not exist

        then:
        revisions.size() == 1
        var revision = revisions.collect().get(0)
        revision.getRevisionNumber() != null
    }

</code></pre>
<p><code>application-tc.yaml</code> overrides the connection parameters to direct to the ephemeral Postgresql instance running in Docker, which is standard when using Testcontainers:</p>
<pre><code>spring:
  datasource:
    url: jdbc:tc:postgresql:13:///test_database
    username: user
    password: password
    driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver
</code></pre>
",https://stackoverflow.com/questions/75527115/integration-testing-spring-data-envers-using-testcontainers-and-spring-boot-data,"['spring-boot', 'testcontainers', 'spring-data-envers']",88,False,1,0
Integration testing and unit testing options for kubernetes deployment (via Openshift),"<p>I am currently deploying application (Ansible automation platform) on Openshift clusters using helm chart and operators. I would like to have worker nodes in Openshift to run as instance group in Ansible automation platform. For this set up is done. Including the deployment via gitlab CICD pipeline.</p>
<p>However, I would like to have unit test, intergration test and performance test for my deployment.
E.G</p>
<ul>
<li>whether Correct release and revision of helm chart is deployed</li>
<li>All resources on Openshift is up</li>
<li>Connectivity to controller</li>
<li>Connectivity to gitlab (scm)</li>
<li>Connectivity between execution nodes (might be with API call)</li>
<li>Running a test job template
(preferably including the test steps to be also included in the pipeline stage)</li>
</ul>
<p>Could you suggest testing options or tools to perform this testing?
Maybe with pros and cons</p>
<p>Thank you</p>
<hr />
<p>I first though about using Helm hook for checking connectivities between kubernetes resources.
Helm hook seems to provide post install options for the life cycle deployment stage.</p>
<p>I wonder whethere there are other options or this options might have cons.</p>
",https://stackoverflow.com/questions/75388057/integration-testing-and-unit-testing-options-for-kubernetes-deployment-via-open,"['kubernetes', 'testing', 'deployment', 'automated-tests', 'openshift']",30,False,0,0
I need advice on Go integration testing using Postgres db in Docker,"<p>I am very new to Go world. I have some db functions that I need to test.
So first I have a database.go file that connects to a postgres db:</p>
<pre><code>import (
    &quot;fmt&quot;
    &quot;gorm.io/driver/postgres&quot;
    &quot;gorm.io/gorm&quot;
    &quot;os&quot;
)

var DB *gorm.DB
var err error

func Open() error {
    dsn := fmt.Sprintf(&quot;host=%s user=%s password=%s dbname=%s port=%s sslmode=disable&quot;, os.Getenv(&quot;HOST&quot;), os.Getenv(&quot;USER&quot;),
        os.Getenv(&quot;PASSWORD&quot;), os.Getenv(&quot;DB&quot;), os.Getenv(&quot;PORT&quot;))
    DB, err = gorm.Open(postgres.Open(dsn), &amp;gorm.Config{})

    if err != nil {
        return err
    }

    return nil
}
</code></pre>
<p>Then I have a customers.go file with functions that interact with that db:</p>
<pre><code>import (
    &quot;customers/cmd/database&quot;
    &quot;time&quot;
)

type Customers struct {
    ID           int       
    CustomerName string   
    Active       bool      
    Balance      float32   
    ActiveSince  time.Time
}

func Get(id int) (Customers, error) {
    var customer Customers
    result := database.DB.First(&amp;customer, id)

    if result.Error != nil {
        return Customers{}, result.Error
    } else {
        return customer, nil
    }
}
</code></pre>
<p>This is all running in docker, there is customers container and postgres container. Now the question is how do I test my <code>Get(id int)</code> function? I was researching dockertest but that spins up a different db and my Get function uses the one I specified in database.go. So is there a standard Go way to test these functions?</p>
",https://stackoverflow.com/questions/75380569/i-need-advice-on-go-integration-testing-using-postgres-db-in-docker,"['postgresql', 'docker', 'go', 'integration-testing']",139,False,2,2
How can I print the widget location during integration testing in Flutter?,"<p><a href=""https://i.stack.imgur.com/sJ7OH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/sJ7OH.png"" alt=""enter image description here"" /></a></p>
<p>While I am debugging integration tests in Flutter, if I set up a breakpoint, I can see the <code>_location</code> property, which shows the exact location of the widget definition in the file. However, I cannot access that property programmatically. How can I print it while running integration tests?</p>
",https://stackoverflow.com/questions/75739456/how-can-i-print-the-widget-location-during-integration-testing-in-flutter,['flutter'],19,False,0,0
Is it possible to do integration testing without mocking the ngrx store?,"<p>My application relies heavily on NgRx store. On startup, large chunks of data are loaded from the backend into the store.</p>
<p>I am trying to define the testing strategy. One option would be integration testing. All what I read says one should mock the store. That seems pretty unreasonable in my case. I wonder whether I should simply initialize the store in beforeAll() and inject the real Store service into the TestBed.</p>
<p>Is there something fundamentally wrong with that idea? Has anyone done it, or a pointer to information on that approach? (I can't find anything in the web)</p>
",https://stackoverflow.com/questions/75302768/is-it-possible-to-do-integration-testing-without-mocking-the-ngrx-store,['angular'],24,False,0,0
Java - Integration testing GraphQL mutations secured methods with @PreAuthorize roles from Keycloak,"<p><strong>What I've got so far:</strong></p>
<ul>
<li>I have working unit tests that return access denied by Spring Security which verifies that my roles are set up correctly with Keycloak.</li>
<li>I have successfully tested a controller that does not have Spring Security implemented and gives the expected result.</li>
<li>I have also tried to run the GraphQl mutation via Insomnia with a service account that has no roles get a 403 forbidden</li>
<li>I have also tried to run the same GraphQl mutation via Insomnia with a service account that has admin role and no role, both mutations carry out successfully. (Screenshots included)</li>
</ul>
<p><strong>Goal:</strong></p>
<ul>
<li>I am trying to write an integration test for my Java Spring project that uses <code>@WithMockUser</code> to simulate a role from Keycloak.</li>
</ul>
<p>Method from controller:</p>
<pre class=""lang-java prettyprint-override""><code>  @MutationMapping
  @PreAuthorize(&quot;hasRole(admin)&quot;)
  public Entity addEntity(@Valid @Argument EntityInput input) {
    var entity =
        Entity.builder()
            .name(input.getName())
            .description(input.getDescription() != null ? input.getDescription() : &quot;&quot;)
            .customId(input.getCustomId() != null ? input.getCustomId() : &quot;&quot;)
            .notBefore(input.getNotBefore().toInstant())
            .expires(input.getExpires() != null ? input.getExpires().toInstant() : null)
            .entityType(input.getEntityType())
            .archived(false)
            .build();

    return entityRepository.persistAndFlush(entity);
  }
</code></pre>
<p>my GraphQl Schema for testing</p>
<pre><code>mutation AddEntity($input: EntityInput!) {
  addEntityl(input: $input) {
    name
    description
    customId
    entityType
    notBefore
    expires
    archived
  }
}
</code></pre>
<p>My test</p>
<pre class=""lang-java prettyprint-override""><code>@Autowired private WebGraphQlTester graphQlTester;

@WithMockUser(username = &quot;Test&quot;, roles={&quot;read_only&quot;})
@Test
void addEntity_with_readonly_role_return_403_forbidden() {
 var entityInput =
 Map.of(
  &quot;customId&quot;,
  &quot;Testing&quot;,
  &quot;name&quot;,
  &quot;Test name&quot;,
  &quot;description&quot;,
  &quot;Test description&quot;,
  &quot;entityType&quot;,
  &quot;MANUAL&quot;,
  &quot;notBefore&quot;,
  &quot;2023-06-28T13:37:00Z&quot;,
  &quot;expires&quot;,
  &quot;2023-07-04T13:37:00Z&quot;);

  graphQlTester
   .documentName(&quot;entities&quot;)
   .operationName(&quot;AddEntity&quot;)
   .variable(&quot;input&quot;, entityInput)
   .execute()
   .errors()
   .satisfy(
     errors -&gt; {
      assertThat(errors).hasSize(1);
      assertThat(errors.get(0).getErrorType()).isEqualTo(ErrorType.FORBIDDEN);
 });
}
</code></pre>
<p>Results from Insomnia:</p>
<p><a href=""https://i.stack.imgur.com/SZx1m.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/SZx1m.png"" alt=""With roles"" /></a>
<a href=""https://i.stack.imgur.com/DCGbe.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/DCGbe.png"" alt=""With no role"" /></a></p>
<p>Edit:</p>
<p>I've also dug a little deeper and found that WebGraphQlTester does not support @WithMockUser as it does not update the security context. If anybody has a workaround or other solution, please post.</p>
",https://stackoverflow.com/questions/75597806/java-integration-testing-graphql-mutations-secured-methods-with-preauthorize,"['java', 'spring-security', 'graphql', 'integration-testing', 'keycloak']",210,False,0,1
How to mock JwtDecoder in Spring Boot for integration testing of authenticated controllers?,"<p>In my Spring Boot application, there are some authenticated controllers.
The operation mode is &quot;OAuth2 resource server&quot;, so my application relies on some arbitrary OAuth2 authorization server. (Let's say it's Keycloak, though it should not affect the way of mocking)</p>
<p>So, the question is:</p>
<p><strong>What is the right way to mock JwtDecoder, in order to be able to pass some static strings as the bearer tokens?</strong></p>
<p>(Please remember, it's a third party server responsible for the token issuing; So I cannot rely on it in tests. I want to mock it away to be able to run tests offline for example)</p>
<p><em>An example of what I expect to happen:</em></p>
<ol>
<li>I mock JwtDecoder (let's pretend I've created some map of &lt;token string, UserData&gt;)</li>
<li>I make a MockMvc-based http call to the authenticated controller with this static string in the Authorization header (Authorization: Bearer STATIC_STRING). The controller test is decorated with <code>@SpringBootTest</code> and <code>@AutoConfigureMockMvc</code>.</li>
<li>I expect to have JwtAuthenticationToken filled with data from UserData from the map of the mocked JwtDecoder.</li>
</ol>
<p><strong>I've already tried</strong> to just create a bean of JwtDecoder implementation with all the described features. I see this bean is added to the configuration, but still whole test ends up in <code>AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext</code>. So I presume that JwtDecoder is never called (checked that with the debugger), and the whole testing setup is misconfigured, but I don't know for sure what to change.</p>
<p>What do I miss?</p>
",https://stackoverflow.com/questions/75464857/how-to-mock-jwtdecoder-in-spring-boot-for-integration-testing-of-authenticated-c,"['spring-boot', 'spring-security', 'jwt', 'integration-testing']",166,True,-1,1
How do you do integration testing of downstream Python projects on GitHub Actions?,"<p>Suppose, you have Projects A and B in their respective repositories with their own unit test workflows. Also, suppose Project B depends on <code>package-a</code> defined by Project A. Now, suppose there is a PR on Project A that increases the minor or patch version of <code>package-a</code>. In that case, we want an integration test workflow from Project A to run the unit test workflow of Project B while making sure that Project B installs the version of <code>package-a</code> that is being worked on. The integration test workflow from Project A should fail if the unit test workflow from Project B fails.</p>
<p>This is complicated by the fact that Project B might need a special environment setup such as starting a database server for executing its tests. Project A shouldn't need to know how to do this environment setup.</p>
<p>I know of <code>repository-dispatch</code> and <code>workflow-dispatch</code> events by GitHub Actions. The problem I am seeing with them is that there is no mechanism to communicate back to the integration test workflow of project A about what happened with the unit test workflow of B.</p>
<p>The solution can make modifications both to Projects A and B.</p>
",https://stackoverflow.com/questions/75155002/how-do-you-do-integration-testing-of-downstream-python-projects-on-github-action,"['python', 'testing', 'continuous-integration', 'github-actions']",31,False,0,0
DNS failure Integration testing a Kafka Streams app with TestContainers and a network alias,"<p>I'm having an unexpected issue trying to link my app under test running in Docker to a Kafka image also running in another Docker container.</p>
<p>I am trying to run by adapting the solution from Alex here: <a href=""https://stackoverflow.com/questions/75388650/testcontainers-schemaregistry-cant-connect-to-kafka-container"">Testcontainers SchemaRegistry can&#39;t connect to Kafka container</a> and have the SchemaRegistryContainer as given in that answer. I am then supplementing that with a Docker image of my test app using the same Docker network.</p>
<p>Based on the documentation on Multi-container usage here <a href=""https://www.testcontainers.org/modules/kafka/"" rel=""nofollow noreferrer"">https://www.testcontainers.org/modules/kafka/</a></p>
<blockquote>
<p>If your test needs to run some other Docker container which needs
access to Kafka, do the following: <br>
... info on running on same Docker network ...
<br> Use <code>kafka.getNetworkAliases().get(0)+&quot;:9092&quot;</code> as bootstrap server location. <br> Or just give your Kafka container a network alias of your liking.</p>
</blockquote>
<p>I tried using the first option, but it complained of not being able to resolve the address by DNS, so I tried setting an alias 'kafka' and connecting via <code>PLAINTEXT://kafka:9092</code>. This also led to the error <code>WARN - Couldn't resolve server PLAINTEXT://kafka:9092 from bootstrap.servers as DNS resolution failed for kafka</code></p>
<p>If I shell into my running container, however, I am able to <code>wget kafka</code> and it resolves to an IP (192.168.128.2 in this case).</p>
<p>I am half anticipating to run into issues with <code>ADVERTISED_LISTENERS</code>, but this seems to be that the Streams app (or at least the Admin client in the streams app) is not able to use the Docker DNS service correctly and isn't even getting to the stage where it can't find the URL returned by Kafka.</p>
",https://stackoverflow.com/questions/76056869/dns-failure-integration-testing-a-kafka-streams-app-with-testcontainers-and-a-ne,"['docker', 'integration-testing', 'apache-kafka-streams', 'testcontainers']",60,False,1,0
How can I add Integration Testing for my Flutter app to my Bitbucket Pipeline?,"<p>I want my Integration Test to run whenever the Bitbucket Pipeline is triggered.</p>
<p>This is my bitbucket-pipelines.yaml file:</p>
<pre><code>definitions:
  services:
    docker:
      memory: 4096
  steps:
  - step: &amp;generate_code
      name: 'generate_code'
      script:
        - flutter clean
        - flutter pub get
        - flutter pub run build_runner build
        - bash &lt;(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh)
        - flutter test
        - git clone git@bitbucket.org:connfair/${CI_PROJECT_NAMESPACE}.git .signing
        - flutter drive \
          --driver=test_driver/integration_test.dart \
          --target=test_driver/run_all_test.dart
      artifacts:
        - lib/**.g.dart
        - lib/**.i18n.dart

</code></pre>
<p>This is my folder structure:</p>
<p><a href=""https://i.stack.imgur.com/nLCFI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/nLCFI.png"" alt=""enter image description here"" /></a></p>
<p>This is my integration_test.dart file:</p>
<pre><code>Future&lt;void&gt; main() =&gt; integrationDriver();

</code></pre>
<p>In the run_all_test.dart file im keeping all my tests:</p>
<pre><code>void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();
  initAppWithMockConfig(config: MockConfig1());
  loginFailureTest();
  loginSuccessTest();
  eventSearchTest(); 
  eventStatisticsAuthorizationTest();
  ticketScannerAuthorizationTest();
}
</code></pre>
<p>This is how one of these tests looks like for example:</p>
<pre><code>void eventSearchTest() {
  testWidgets(&quot;After choosing an event from the event search delegate, &quot;
      &quot;the event's name gets displayed 2 times: in the event dashbaord and in the appbar.&quot;,
          (WidgetTester tester) async {

        await tester.pumpWidget(
          wrapWithUser(wrapWithProviders(wrapWithApp(MainframeContent()))),
        );
        await tester.pumpAndSettle();

        await selectEventFromDashboard(tester, getValidEventId());

        expect(find.text(getValidEventName()), findsWidgets);
      });
}
</code></pre>
<p>When I run</p>
<ul>
<li>flutter drive <br />
--driver=test_driver/integration_test.dart <br />
--target=test_driver/run_all_test.dart</li>
</ul>
<p>in the Terminal while an emulator is open everything works fine. But when I let the pipeline run with the same comment Im getting an Error. I also tried adding build apk before my flutter drive command. This is the error im getting:</p>
<p><a href=""https://i.stack.imgur.com/WShBU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WShBU.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75922728/how-can-i-add-integration-testing-for-my-flutter-app-to-my-bitbucket-pipeline,"['flutter', 'bitbucket', 'bitbucket-pipelines', 'flutter-integration-test']",63,False,0,0
How do I perform integration testing with Azure DevOps Pipelines for monitoring file flow?,"<p>I need some guidance for Integraion Testing with Azure DevOps Pipelines.</p>
<p>I'm totally new to DevOps.</p>
<p>The application I need to test monitor folders for new files, once new files are detected they are loaded and teated and then moved to another folder.
There is more to it like file format checking, treatment parameters loading and checking from a database...</p>
<p>I need to test that files are correctly loaded and treated, by checking the folder move flow and file process steps logged in log files.</p>
<p>Basically all steps we do manually after code modification.</p>
<p>I guess steps would be:</p>
<ul>
<li>clone code</li>
<li>load dependencies</li>
<li>compile</li>
<li>start the programme</li>
<li>move test files in monitored folder</li>
<li>check file presences in folders</li>
<li>check log for keywords</li>
<li>build and save/send repport</li>
</ul>
<p>For what I google, this is integration testing not Unit testing.</p>
<p>I wonder if I can use standard Testing framework (xUnit, NUnit, MSTest... ) or a special framework ?
I found reference about Celenium and Appium but they lok to be targeted towards web app/site testing.</p>
<p>I also see reference to Visual Studio test plarform, but for what I understand look to be for unit testing !?</p>
<p>Any suggestions ?</p>
<p>Thanks and regards</p>
",https://stackoverflow.com/questions/76341854/how-do-i-perform-integration-testing-with-azure-devops-pipelines-for-monitoring,"['testing', 'azure-devops', 'azure-pipelines', 'integration']",18,False,-1,0
Using cucumber android in unit testing &quot;test&quot; directory and not in &quot;androidTest&quot; for integration testing,"<p>I'm trying to use cucumber-android for integration testing in &quot;test&quot; directory. All the code samples/examples I found use &quot;androidTest&quot; directory and UI tests.</p>
<p>I'm looking to use cucumber for integration testing of several different components, without UI, to start with.</p>
<p>For example, I want to integration test viewModel. Here is my sample code.</p>
<pre><code>@CucumberOptions(
    features = [&quot;src/test/assets/features&quot;],
    glue = [&quot;com.example.mysteps&quot;]
)
class MyIntegrationTest : BaseIntegrationTest() {

    @Test
    fun `runCucumber`() {
        Cucumber(CheckoutIntegrationTest::java).run() 
    }
}
</code></pre>
<p>And my steps class is</p>
<pre><code>class Steps {   

    @Given(&quot;^The vendor is selected for delivery type$&quot;)
    fun `test given`() {
        println(&quot;### given&quot;)
    }

    @When(&quot;^Time picker is loaded$&quot;)
    fun `test when`()
        println(&quot;### when&quot;)
    }

    @Then(&quot;^The vendor is available with different timeslots$&quot;)
    fun `test then`() {
        println(&quot;### then&quot;)
    }
}
</code></pre>
<p>There are a few questions.</p>
<ol>
<li>How can I inject the objects into Steps class from my dagger object graph? We are using Anvil and not pico-container.</li>
<li>What are various ways of running a cucumber test? I'm currently running from Android studio's run button.</li>
</ol>
",https://stackoverflow.com/questions/76227465/using-cucumber-android-in-unit-testing-test-directory-and-not-in-androidtest,"['android', 'cucumber', 'cucumber-jvm', 'cucumber-junit']",16,False,0,0
How to do Integration testing for post actions that require anti-forgery token and authentication,"<p>I am currently doing integration testing for my application which is a job portal system made with Asp.net core 6 MVC.</p>
<p>I can test Post actions like SignUp post Action method that require anti forgery token, or Get Action methods that require Authentication by creating the clients the following ways:</p>
<p>for anti forgery</p>
<pre><code>            using var cookieHandler = new CookieContainerHandler();
            cookieHandler.Container.Add(
                _factory.Server.BaseAddress,
                new Cookie(antiforgeryTokens.CookieName, antiforgeryTokens.CookieValue));


            using var client = _factory.CreateDefaultClient(cookieHandler);
</code></pre>
<p>for Auth</p>
<pre><code>
            var provider = TestClaimsProvider.WithCompanyClaims();
            _client = _factory.CreateClientWithTestAuth(provider);
</code></pre>
<p>But I am facing issue with testing Post actions that require Authentication and anti forgery token like the following:</p>
<pre><code>        [HttpPost]
        [Authorize(Roles =Roles.Company)]
        [ValidateAntiForgeryToken]
        public async Task&lt;IActionResult&gt; PostJob(JobPostingViewModel viewModel)
</code></pre>
<p>I would appreciate it if somebody showed me how to integration testing for post actions that require [Authorize(Roles =Roles.Company)] and [ValidateAntiForgeryToken]</p>
<p>I have came up with this test but its not working</p>
<pre><code>        [Fact]
        public async Task PostJob_ValidModel_ReturnsRedirectToAction()
        {
            // Arrange
            //var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
            //{
            //    AllowAutoRedirect = false // Prevent automatic redirects in the test client
            //});

            //var responset = await _client.GetAsync(&quot;/CompanyArea/Jobs/PostJob&quot;);
            //var antiforgeryToken = responset.Headers
            //    .FirstOrDefault(c =&gt; c.Key == &quot;Set-Cookie&quot;).Value.FirstOrDefault();
            //antiforgeryToken=antiforgeryToken.Replace(&quot;.AspNetCore.Antiforgery.&quot;, &quot;&quot;);

            //antiforgeryToken=antiforgeryToken.Replace(&quot;; path=/; secure; samesite=strict; httponly&quot;,&quot;&quot;);
            var antiforgeryTokens = await _factory.GetAntiforgeryTokensAsync();

            using var cookieHandler = new CookieContainerHandler();
            cookieHandler.Container.Add(
                _factory.Server.BaseAddress,
                new Cookie(antiforgeryTokens.CookieName, antiforgeryTokens.CookieValue));


            using var client = _factory.CreateDefaultClient(cookieHandler);
            client.DefaultRequestHeaders.Authorization= new AuthenticationHeaderValue(&quot;Test&quot;);

            var viewModel = new JobPostingViewModel
            {
                FieldId = 1,
                Description = &quot;Test job posting&quot;,
                JobType = &quot;Full-time&quot;,
                RequiredDegreeIds = new List&lt;int&gt; { 1, 2 },
                RequiredSkillIds = new List&lt;int&gt; { 3, 4 },
                Title = &quot;Test job&quot;
            };
            var formData = new Dictionary&lt;string, string&gt;
        {
            { &quot;__RequestVerificationToken&quot;, antiforgeryTokens.CookieValue },
            { &quot;FieldId&quot;, viewModel.FieldId.ToString() },
            { &quot;Description&quot;, viewModel.Description },
            { &quot;JobType&quot;, viewModel.JobType },
            { &quot;RequiredDegreeIds&quot;, string.Join(&quot;,&quot;, viewModel.RequiredDegreeIds) },
            { &quot;RequiredSkillIds&quot;, string.Join(&quot;,&quot;, viewModel.RequiredSkillIds) },
            { &quot;Title&quot;, viewModel.Title }
        };
            var content = new FormUrlEncodedContent(formData);
            // Act
            var response = await client.PostAsync(&quot;/CompanyArea/Jobs/PostJob&quot;, content);

            // Assert
            Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); // Check that the response is a redirect
            Assert.Equal(&quot;/CompanyArea/Jobs/PostedJobs&quot;, response.Headers.Location.OriginalString); // Check that the redirect location is correct
        }
</code></pre>
",https://stackoverflow.com/questions/76114969/how-to-do-integration-testing-for-post-actions-that-require-anti-forgery-token-a,"['c#', 'asp.net-core', 'asp.net-core-mvc', 'integration-testing', 'xunit']",65,False,0,0
How to Set HTTP_HOST while Integration Testing via PHPUnit on multitenant Laravel app with different domain,"<p>I have a multitenant application, in which every tenant has a specific domain or subdomain.
some of these tenants like the landlord have some particular features and tools.</p>
<p>I've managed to initialize HTTP_HOST in PHPUnit by adding the following line:
<code>&lt;server name='HTTP_HOST' value='mydomain.local' /&gt;</code>
but doing this, I must manually change the HTTP_HOST every time and re-run the tests to cover all the scenarios.</p>
<p>is there any way to set this dynamically?</p>
<p>using <code>-&gt;withHeaders(['HTTP_HOST' =&gt; 'mydomain.local'])</code> won't work.</p>
",https://stackoverflow.com/questions/75082345/how-to-set-http-host-while-integration-testing-via-phpunit-on-multitenant-larave,"['php', 'laravel', 'phpunit']",79,False,1,1
Way to do a proper integration testing with firebase emulators with all services at same time,"<p>I want to test my firebase back-end involving firestore, auth, and functions. There are cloud functions on new user created or deleted and rest like apis all affecting firestore data.</p>
<p><strong>I want to run test like this.</strong></p>
<ol>
<li><p>I will start firebase emulator (with no data) in a terminal.</p>
</li>
<li><p>Run test file. Following everything will be in a script, so no part is manual.</p>
</li>
<li><p>I will register new users. Those should trigger firebase functions lets say affecting <code>users</code> collection.</p>
</li>
<li><p>Test if the <code>users</code> collection is affected.</p>
</li>
<li><p>Then do a fake login with any created user say <code>Jake Williams</code>.</p>
</li>
<li><p>Call some rest api. Those api will again change firestore data. For these cloud functions <code>auth</code> received will be of <code>Jake Williams</code></p>
</li>
<li><p>Test if those firestore data is affected.</p>
</li>
<li><p>Clean emulator data and run other tests.</p>
</li>
</ol>
<p>I have gone through docs, yet these is unclear. Went through <a href=""https://github.com/firebase/quickstart-testing"" rel=""nofollow noreferrer"">github/quickStart-testing</a>, still no help. I see there are tutorial which test firestore rules and some test cloud functions separately.</p>
<p>Can I setup a test project to work like my above requirements?</p>
",https://stackoverflow.com/questions/75413721/way-to-do-a-proper-integration-testing-with-firebase-emulators-with-all-services,"['firebase', 'testing', 'google-cloud-firestore', 'google-cloud-functions', 'firebase-tools']",159,True,0,1
Is it good to call another test method in integration testing because it requires multiple steps?,"<p>How can I create integration tests for a password reset functionality with the following conditions:</p>
<p>The function should reset the password
The first step is to make a POST request to /forgot-password to generate an OTP. If successful, a &quot;token&quot; will be sent back to be used for the following requests.
The next step is to make a POST request to /verify-code with the &quot;token&quot; obtained from the previous step.</p>
<p>Finally, make a POST request to /reset-password with the same &quot;token&quot; that has been verified in the previous step.
Is it a good practice to call a previous test method in each test case? For example, having test methods like testSendVerificationCode and testVerifyCode where testVerifyCode calls testSendVerificationCode before running its own tests.</p>
<pre class=""lang-py prettyprint-override""><code>import unittest

class PasswordResetIntegrationTest(unittest.TestCase):
    def test_send_verification_code(self):
        # make a POST request to /forgot-password to generate OTP
        # assert that a &quot;token&quot; is returned

    def test_verify_code(self):
        # call test_send_verification_code method
        # make a POST request to /verify-code with the token obtained from test_send_verification_code
        # assert that the response status code is 200

    def test_reset_password(self):
        # call test_send_verification_code method and test_verify_code method
        # make a POST request to /reset-password with the token obtained from test_send_verification_code
        # assert that the response status code is 200
</code></pre>
",https://stackoverflow.com/questions/75617517/is-it-good-to-call-another-test-method-in-integration-testing-because-it-require,"['unit-testing', 'integration-testing']",34,False,0,0
"Getting &quot;TypeError: (0 , _firestore.getFirestore) is not a function&quot; When trying to perform integration testing with Jest, Firebase and Expo","<p>I am getting the error &quot;TypeError: (0 , _firestore.getFirestore) is not a function&quot; When trying to run a Jest integration test with my app's Login page. It seems that Jest is unable to recognise it as a function despite the rest of my Expo app being able to recognise it just fine.</p>
<p>I am wondering if this is because My firebase config file uses Web Version 9 as required by Expo and if there are any solutions or alternatives to this.</p>
<p>Thanks</p>
<pre><code>import { initializeApp } from 'firebase/app';
import { getFirestore } from &quot;firebase/firestore&quot;;

// Firebase API
const firebaseConfig = {

  };

const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
</code></pre>
<p>I have tried import { firestore } from &quot;firebase/firestore&quot;, import &quot;firebase/firestore&quot;,</p>
<p>export const db+ app.firestore().</p>
<p>None of them works.</p>
<p>This is my package.json</p>
<pre><code>{
  &quot;name&quot;: &quot;test&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;main&quot;: &quot;node_modules/expo/AppEntry.js&quot;,
  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;expo start&quot;,
    &quot;android&quot;: &quot;expo start --android&quot;,
    &quot;ios&quot;: &quot;expo start --ios&quot;,
    &quot;web&quot;: &quot;expo start --web&quot;
  },
  &quot;dependencies&quot;: {
    &quot;@emailjs/browser&quot;: &quot;^3.10.0&quot;,
    &quot;@expo/dev-server&quot;: &quot;0.1.120&quot;,
    &quot;@expo/webpack-config&quot;: &quot;^0.17.0&quot;,
    &quot;@react-native-async-storage/async-storage&quot;: &quot;~1.17.3&quot;,
    &quot;@react-native-community/clipboard&quot;: &quot;^1.5.1&quot;,
    &quot;@react-native-community/datetimepicker&quot;: &quot;6.5.2&quot;,
    &quot;@react-native-community/masked-view&quot;: &quot;^0.1.11&quot;,
    &quot;@react-native-picker/picker&quot;: &quot;2.4.8&quot;,
    &quot;@react-navigation/bottom-tabs&quot;: &quot;^6.4.0&quot;,
    &quot;@react-navigation/native&quot;: &quot;^6.0.13&quot;,
    &quot;@react-navigation/stack&quot;: &quot;^6.3.3&quot;,
    &quot;@twotalltotems/react-native-otp-input&quot;: &quot;1.3.7&quot;,
    &quot;base-64&quot;: &quot;^1.0.0&quot;,
    &quot;expo&quot;: &quot;^47.0.8&quot;,
    &quot;expo-checkbox&quot;: &quot;~2.2.0&quot;,
    &quot;expo-document-picker&quot;: &quot;~11.0.1&quot;,
    &quot;expo-image-picker&quot;: &quot;~14.0.2&quot;,
    &quot;expo-location&quot;: &quot;~15.0.1&quot;,
    &quot;expo-status-bar&quot;: &quot;~1.4.0&quot;,
    &quot;expo-web-browser&quot;: &quot;~12.0.0&quot;,
    &quot;firebase&quot;: &quot;^9.16.0&quot;,
    &quot;jest&quot;: &quot;^26.6.3&quot;,
    &quot;jest-expo&quot;: &quot;^47.0.1&quot;,
    &quot;leo-profanity&quot;: &quot;^1.7.0&quot;,
    &quot;lottie-react-native&quot;: &quot;^5.1.4&quot;,
    &quot;moment&quot;: &quot;^2.29.4&quot;,
    &quot;parse&quot;: &quot;^4.0.0&quot;,
    &quot;react&quot;: &quot;18.1.0&quot;,
    &quot;react-dom&quot;: &quot;18.1.0&quot;,
    &quot;react-hook-form&quot;: &quot;^7.42.0&quot;,
    &quot;react-native&quot;: &quot;0.70.5&quot;,
    &quot;react-native-draggable-flatlist&quot;: &quot;^4.0.0&quot;,
    &quot;react-native-dropdown-select-list&quot;: &quot;^2.0.4&quot;,
    &quot;react-native-gesture-handler&quot;: &quot;~2.8.0&quot;,
    &quot;react-native-google-places-autocomplete&quot;: &quot;^2.5.1&quot;,
    &quot;react-native-keyboard-aware-scroll-view&quot;: &quot;^0.9.5&quot;,
    &quot;react-native-keychain&quot;: &quot;^8.1.1&quot;,
    &quot;react-native-maps&quot;: &quot;1.3.2&quot;,
    &quot;react-native-maps-directions&quot;: &quot;^1.9.0&quot;,
    &quot;react-native-modal-datetime-picker&quot;: &quot;^14.0.1&quot;,
    &quot;react-native-otp-input&quot;: &quot;^1.0.12&quot;,
    &quot;react-native-paper&quot;: &quot;^4.12.5&quot;,
    &quot;react-native-picker-select&quot;: &quot;^8.0.4&quot;,
    &quot;react-native-reanimated&quot;: &quot;~2.12.0&quot;,
    &quot;react-native-reanimated-carousel&quot;: &quot;^3.1.5&quot;,
    &quot;react-native-safe-area-context&quot;: &quot;4.4.1&quot;,
    &quot;react-native-screens&quot;: &quot;~3.18.0&quot;,
    &quot;react-native-uuid&quot;: &quot;^2.0.1&quot;,
    &quot;react-native-web&quot;: &quot;~0.18.7&quot;,
    &quot;react-native-webview&quot;: &quot;11.23.1&quot;,
    &quot;rn-credit-card&quot;: &quot;^1.0.4&quot;,
    &quot;uniqid&quot;: &quot;^5.4.0&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.12.9&quot;,
    &quot;@testing-library/react-native&quot;: &quot;^11.5.1&quot;
  },
  &quot;jest&quot;: {
    &quot;preset&quot;: &quot;jest-expo&quot;,
    &quot;transformIgnorePatterns&quot;: [
      &quot;node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)&quot;
    ]
  },
  &quot;private&quot;: true
}
</code></pre>
",https://stackoverflow.com/questions/75342494/getting-typeerror-0-firestore-getfirestore-is-not-a-function-when-trying,"['javascript', 'firebase', 'react-native', 'google-cloud-firestore', 'jestjs']",66,False,0,0
Web layer testing in spring boot with MockMvc,"<p>I am writing integration testing for rest apis in spring boot</p>
<p>I wrote an annotation for Integration testing</p>
<pre><code>@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(classes = {ShopAppApplication.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public @interface IntegrationTest {
}

</code></pre>
<p>And this is my controller test class</p>
<pre><code>
@IntegrationTest
@AutoConfigureMockMvc
@ActiveProfiles(&quot;test&quot;)
@WithMockUser
public class AuthControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private AuthService authService;

    @Test
    @Transactional
    void shouldRegister() throws Exception {

        UserRegisterDto registerDto = new UserRegisterDto(
                &quot;user1&quot;,
                &quot;user1&quot;,
                &quot;+998931112233&quot;,
                &quot;123&quot;);

        ApiResult&lt;Void&gt; result = ApiResult.successResponse();
        when(authService.register(ArgumentMatchers.any())).thenReturn(result);
        mvc.perform(MockMvcRequestBuilders
                        .post(AuthController.REGISTER_URL)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(TestUtil.convertObjectToJsonBytes(registerDto)))
                .andDo(print())
                .andExpect(status().isCreated());

    }
}


</code></pre>
<p>And AuthService class</p>
<pre><code>
  @Override
    public ApiResult&lt;Void&gt; register(UserRegisterDto dto) {
        log.info(&quot;User registration with &quot; + dto);

        if (userRepository.existsByPhoneNumber(dto.getPhoneNumber()))
            throw new ConflictException(messageSource.getMessage(&quot;PHONE_NUMBER_ALREADY_EXISTS&quot;, null, LocaleContextHolder.getLocale()));

        User user = userMapper.fromAddDto(dto);
        user.setPassword(passwordEncoder.encode(dto.getPassword()));
        user.setActive(true);
        userRepository.save(user);
        return ApiResult.successResponse();
    }

</code></pre>
<p>MockMvc can not find controller
and this exception occurs</p>
<p>I debug test also but it can not go to controller</p>
<pre><code>
java.lang.AssertionError: Status expected:&lt;200&gt; but was:&lt;404&gt;
Expected :200
Actual   :404
&lt;Click to see difference&gt;


</code></pre>
",https://stackoverflow.com/questions/75373159/web-layer-testing-in-spring-boot-with-mockmvc,"['spring-boot-test', 'mockmvc']",16,False,0,0
Springboot 2.7(JDK 17) Integration Test Initialization failing with Unable to make field static final,"<p>I'm working on Springboot integration testing on JDK17 and am getting below error while starting the test from IntelliJ.</p>
<pre><code>Invocation of init method failed; nested exception is java.lang.reflect.InaccessibleObjectException: Unable to make field static final java.lang.invoke.MethodHandles$Lookup java.lang.invoke.MethodHandles$Lookup.IMPL_LOOKUP accessible: module java.base does not &quot;opens java.lang.invoke&quot; to unnamed module @7c0e2abd
</code></pre>
<p>I tried adding the below VM options for <code>JUnit template</code> as <code>Run/Debug</code> configurations of the test am running but still am getting the above error, can someone please help me fixing above error to start integration testing from IntelliJ?</p>
<pre><code>--add-opens jdk.naming.rmi/com.sun.jndi.rmi.registry=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/sun.security.action=ALL-UNNAMED --add-opens java.base/sun.net=ALL-UNNAMED --add-opens java.base/java.lang.invoke=ALL-UNNAMED
</code></pre>
",https://stackoverflow.com/questions/75552793/springboot-2-7jdk-17-integration-test-initialization-failing-with-unable-to-ma,"['java', 'spring-boot', 'junit', 'java-17']",277,False,0,0
How to do Integration testing for post actions that require anti-forgery token and authentication,"<p>I am currently doing integration testing for my application which is a job portal system made with Asp.net core 6 MVC.</p>
<p>I can test Post actions like SignUp post Action method that require anti forgery token, or Get Action methods that require Authentication by creating the clients the following ways:</p>
<p>for anti forgery</p>
<pre><code>            using var cookieHandler = new CookieContainerHandler();
            cookieHandler.Container.Add(
                _factory.Server.BaseAddress,
                new Cookie(antiforgeryTokens.CookieName, antiforgeryTokens.CookieValue));


            using var client = _factory.CreateDefaultClient(cookieHandler);
</code></pre>
<p>for Auth</p>
<pre><code>
            var provider = TestClaimsProvider.WithCompanyClaims();
            _client = _factory.CreateClientWithTestAuth(provider);
</code></pre>
<p>But I am facing issue with testing Post actions that require Authentication and anti forgery token like the following:</p>
<pre><code>        [HttpPost]
        [Authorize(Roles =Roles.Company)]
        [ValidateAntiForgeryToken]
        public async Task&lt;IActionResult&gt; PostJob(JobPostingViewModel viewModel)
</code></pre>
<p>I would appreciate it if somebody showed me how to integration testing for post actions that require [Authorize(Roles =Roles.Company)] and [ValidateAntiForgeryToken]</p>
<p>I have came up with this test but its not working</p>
<pre><code>        [Fact]
        public async Task PostJob_ValidModel_ReturnsRedirectToAction()
        {
            // Arrange
            //var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
            //{
            //    AllowAutoRedirect = false // Prevent automatic redirects in the test client
            //});

            //var responset = await _client.GetAsync(&quot;/CompanyArea/Jobs/PostJob&quot;);
            //var antiforgeryToken = responset.Headers
            //    .FirstOrDefault(c =&gt; c.Key == &quot;Set-Cookie&quot;).Value.FirstOrDefault();
            //antiforgeryToken=antiforgeryToken.Replace(&quot;.AspNetCore.Antiforgery.&quot;, &quot;&quot;);

            //antiforgeryToken=antiforgeryToken.Replace(&quot;; path=/; secure; samesite=strict; httponly&quot;,&quot;&quot;);
            var antiforgeryTokens = await _factory.GetAntiforgeryTokensAsync();

            using var cookieHandler = new CookieContainerHandler();
            cookieHandler.Container.Add(
                _factory.Server.BaseAddress,
                new Cookie(antiforgeryTokens.CookieName, antiforgeryTokens.CookieValue));


            using var client = _factory.CreateDefaultClient(cookieHandler);
            client.DefaultRequestHeaders.Authorization= new AuthenticationHeaderValue(&quot;Test&quot;);

            var viewModel = new JobPostingViewModel
            {
                FieldId = 1,
                Description = &quot;Test job posting&quot;,
                JobType = &quot;Full-time&quot;,
                RequiredDegreeIds = new List&lt;int&gt; { 1, 2 },
                RequiredSkillIds = new List&lt;int&gt; { 3, 4 },
                Title = &quot;Test job&quot;
            };
            var formData = new Dictionary&lt;string, string&gt;
        {
            { &quot;__RequestVerificationToken&quot;, antiforgeryTokens.CookieValue },
            { &quot;FieldId&quot;, viewModel.FieldId.ToString() },
            { &quot;Description&quot;, viewModel.Description },
            { &quot;JobType&quot;, viewModel.JobType },
            { &quot;RequiredDegreeIds&quot;, string.Join(&quot;,&quot;, viewModel.RequiredDegreeIds) },
            { &quot;RequiredSkillIds&quot;, string.Join(&quot;,&quot;, viewModel.RequiredSkillIds) },
            { &quot;Title&quot;, viewModel.Title }
        };
            var content = new FormUrlEncodedContent(formData);
            // Act
            var response = await client.PostAsync(&quot;/CompanyArea/Jobs/PostJob&quot;, content);

            // Assert
            Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); // Check that the response is a redirect
            Assert.Equal(&quot;/CompanyArea/Jobs/PostedJobs&quot;, response.Headers.Location.OriginalString); // Check that the redirect location is correct
        }
</code></pre>
",https://stackoverflow.com/questions/76114969/how-to-do-integration-testing-for-post-actions-that-require-anti-forgery-token-a,"['c#', 'asp.net-core', 'asp.net-core-mvc', 'integration-testing', 'xunit']",65,False,0,0
Using cucumber android in unit testing &quot;test&quot; directory and not in &quot;androidTest&quot; for integration testing,"<p>I'm trying to use cucumber-android for integration testing in &quot;test&quot; directory. All the code samples/examples I found use &quot;androidTest&quot; directory and UI tests.</p>
<p>I'm looking to use cucumber for integration testing of several different components, without UI, to start with.</p>
<p>For example, I want to integration test viewModel. Here is my sample code.</p>
<pre><code>@CucumberOptions(
    features = [&quot;src/test/assets/features&quot;],
    glue = [&quot;com.example.mysteps&quot;]
)
class MyIntegrationTest : BaseIntegrationTest() {

    @Test
    fun `runCucumber`() {
        Cucumber(CheckoutIntegrationTest::java).run() 
    }
}
</code></pre>
<p>And my steps class is</p>
<pre><code>class Steps {   

    @Given(&quot;^The vendor is selected for delivery type$&quot;)
    fun `test given`() {
        println(&quot;### given&quot;)
    }

    @When(&quot;^Time picker is loaded$&quot;)
    fun `test when`()
        println(&quot;### when&quot;)
    }

    @Then(&quot;^The vendor is available with different timeslots$&quot;)
    fun `test then`() {
        println(&quot;### then&quot;)
    }
}
</code></pre>
<p>There are a few questions.</p>
<ol>
<li>How can I inject the objects into Steps class from my dagger object graph? We are using Anvil and not pico-container.</li>
<li>What are various ways of running a cucumber test? I'm currently running from Android studio's run button.</li>
</ol>
",https://stackoverflow.com/questions/76227465/using-cucumber-android-in-unit-testing-test-directory-and-not-in-androidtest,"['android', 'cucumber', 'cucumber-jvm', 'cucumber-junit']",16,False,0,0
How to write integration test case to test API using vertx?,"<pre class=""lang-java prettyprint-override""><code>@Test
public void dummyTestCase() {
    System.out.println(&quot; dummyTestCase &quot;);
    HttpClient client = vertx.createHttpClient();
    client.request(HttpMethod.GET, 8080, &quot;localhost&quot;, &quot;/api/user&quot;, 
            HttpClientResponse -&gt; {
                    System.out.println(&quot; dummyTestCase inside &quot;);
                    context.assertEquals(HttpClientResponse.statusCode(), 200);
            });
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Test
public void getUsers() {
    System.out.println(&quot;Inside getusers &quot;);
    Async async = context.async();
    vertx.createHttpClient().get(&quot;localhost&quot;, &quot;/api/user&quot;, 
            response -&gt; {
                    System.out.println(&quot;Inside vertx&quot;);
                    context.assertEquals(response.statusCode(), 200);
                    context.assertEquals(response.headers().get(&quot;content-type&quot;), &quot;application/json&quot;);
                    response.bodyHandler(body -&gt; {
                        context.assertTrue(body.toString().contains(&quot;Collection&quot;));
                        async.complete();
                    });
            });
}
</code></pre>
<p>I've tried creating integration testing to test API like above two ways but the end point mentioned was not calling. Below is my <code>serviceVertical</code> class snippet.</p>
<pre class=""lang-java prettyprint-override""><code>@Override
public void start() throws Exception {

    // Server Configuration
    final HttpServerOptions serverOptions = new HttpServerOptions()
            .setCompressionSupported(config().getBoolean(&quot;api.compress&quot;, true))
        .setCompressionLevel(config().getInteger(&quot;api.compress.level&quot;, 7))
        .setDecompressionSupported(config().getBoolean(&quot;api.compress&quot;, true))
        .setHost(config().getString(&quot;api.host&quot;, &quot;0.0.0.0&quot;))
        .setPort(config().getInteger(&quot;api.port&quot;, 8080));

    final Router router = Router.router(vertx);
    final HttpServer httpServer = vertx.createHttpServer(serverOptions);

    logger.info(&quot;Info&quot;);
    if (!config().getBoolean(&quot;authentication.bypass&quot;,false)) {
        AuthHandler authHandler = JWTAuthHandler.create(new JWTAuth(
                config().getString(&quot;authentication.issuer&quot;),
                config().getBoolean(&quot;authentication.bypass&quot;), 
                config().getString(&quot;authentication.clientid&quot;)),
                &quot;/api/camel/sample&quot;);
        router.route(&quot;/api/*&quot;).handler(authHandler);
    }

    UserService userService = new UserService(config(), vertx);
    GroupService groupService = new GroupService(config());
    AllService allService = new AllService(config(), vertx);

    // users
    router.route().handler(BodyHandler.create());
    router.route(HttpMethod.GET, &quot;/api/user&quot;).handler(e -&gt; { userService.getUsers(e); });
        
    httpServer.requestHandler(router::accept).listen();
    logger.info(&quot;Service verticle started.&quot;);

}
</code></pre>
<p>I tried calling the endpoint in the ways mentioned above but they did not work.</p>
",https://stackoverflow.com/questions/75654473/how-to-write-integration-test-case-to-test-api-using-vertx,"['junit5', 'vert.x', 'vertx-httpclient']",51,False,0,0
Should I write unit test for the @KafkaListener,"<p>I have a Kafka consumer which uses <code>@KafkaListener</code>. But the listener does nothing except receiving the message and pass it to private method to do the necessary things. My question is I am wondering whether I need to write integration testing to see listener is working or just the unit test. If I write unit test again the <code>@KafkaListener</code> annotated method is not doing much and just pass the message to relevant private method. So in that case, I cannot write unit tests for private methods. See below receiver code.</p>
<pre><code>@Service
@Slf4j
class KafkaConsumerService {

    @KafkaListener(
        groupId = &quot;#{groupId('listener')}&quot;,
        topics = [&quot;#{pubTopic('someTopic')}&quot;]
    )
    fun process(@Payload message: EventMessage) {
        log.info(&quot;Received a message &gt; &quot;)
        when (message.type) {
            Type1 -&gt; processMessageType1(message.type1Mesage)
            Type2 -&gt; processMessageType2(message.type2Mesage)
            else -&gt; log.info(&quot;unhandled type &quot;)
        }
    }

    private fun processMessageType1(message: Type1Mesage) {
        log.warn(&quot;Received a Type1Mesage &quot; )
        val someClassObj = SomeClass()
        someClassObj.publicMethod(message)
    }

    private fun processMessageType2(message: Type2Mesage) {
        log.warn(&quot;Received a Type2Mesage &quot;)
        val someClassObj = SomeClass()
        someClassObj.publicMethod(message)
    }   
}
</code></pre>
<p>How can I test this? or there is no need to do Unit Testing here? I wrote some integration testing to see whether the listener is working but it did not work. Appreciate expert's advise.</p>
",https://stackoverflow.com/questions/76007690/should-i-write-unit-test-for-the-kafkalistener,"['unit-testing', 'apache-kafka', 'junit', 'integration-testing', 'spring-kafka']",63,True,0,1
Which API or cmd to use to emit the metadata or counterdata for go code coverage?,"<p>As mentioned in <a href=""https://go.googlesource.com/proposal/+/master/design/51430-revamp-code-coverage.md"" rel=""nofollow noreferrer"">https://go.googlesource.com/proposal/+/master/design/51430-revamp-code-coverage.md</a>, which API or cli option to use to emit the Go code coverage out for the server programs which are long running or never exits.</p>
<p>Expectation is that Code Coverage is generated after the system/integration testing of Golang application.</p>
",https://stackoverflow.com/questions/76254028/which-api-or-cmd-to-use-to-emit-the-metadata-or-counterdata-for-go-code-coverage,"['go', 'code-coverage']",32,False,-3,0
Wiremock integration with spring boot is throwing 404 exception as &quot;Request did not match as stub is not registered&quot;,"<p>I have been using wiremock for integration testing with spring boot, getting 404 exception.</p>
<p>With message as &quot;Request did not match, as no stubs registered&quot;</p>
<p>I have tried with wiremock server and wiremock rule instance.</p>
<p>Tried with Wiremock's JUnit jupiter extension approach and Application context initializer approach, nothing seems to be work.</p>
<pre><code>package fi.op.bcsio.application.wiremock;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

import java.util.function.Supplier;

import static com.github.tomakehurst.wiremock.client.WireMock.*;

import javax.annotation.PostConstruct;

import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.client.RestTemplate;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.common.ConsoleNotifier;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockClassRule;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;

import org.assertj.core.api.Assertions;

@Component
//@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//@ContextConfiguration(initializers = {WireMockInitializer.class})
public class LuukuWiremockStub {

//    @Autowired
//    private WebTestClient webTestClient;
    
    
//  @ClassRule
//  public static WireMockRule wireMockRule = new WireMockRule(WireMockConfiguration.DYNAMIC_PORT);

      @RegisterExtension
      static WireMockExtension wireMockServer = WireMockExtension.newInstance()
        .options(WireMockConfiguration.options().dynamicPort())
        .build();

//    @DynamicPropertySource
//    static void configureProperties(DynamicPropertyRegistry registry) {
//      registry.add(&quot;http://op-common.apis.jty.op-palvelut.net/bankingparties/basic/info/v1/parties?context=Pankin ostopolku&quot;, wireMockServer::baseUrl);
//    }

//    @AfterEach
//    void resetAll() {
//      // we're using one WireMock server for the test class (see static on the WireMockExtension definition)
//        wireMockRule.resetAll();
//    }

      @Test
      void testGetAllTodosShouldReturnDataFromClient() {
          wireMockServer.stubFor(
          WireMock.get(&quot;/parties&quot;)
          
          .withHeader(&quot;x-request-id&quot;, matching(&quot;[0-9a-fA-F]{8}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{12}&quot;))
          
            .withHeader(&quot;x-session-id&quot;, matching(&quot;[0-9a-fA-F]{8}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{12}&quot;))
                      
            .withHeader(&quot;x-api-key&quot;, equalTo(&quot;X8Jy6AEXqJjdBx&quot;))
                      
            .withHeader(&quot;Authorization&quot;, matching(&quot;Bearer [a-zA-Z0-9&amp;._-]{1,}&quot;))
            
            .withQueryParam(&quot;context&quot;, equalTo(&quot;Pankin ostopolku&quot;))
          
            .willReturn(aResponse()
            
            .withHeader(&quot;Content-Type&quot;, MediaType.APPLICATION_JSON_VALUE)
              
            .withBody(&quot;[{\&quot;userId\&quot;: 1,\&quot;id\&quot;: 1,\&quot;title\&quot;: \&quot;Learn Spring Boot 3.0\&quot;, \&quot;completed\&quot;: false},&quot; +
                &quot;{\&quot;userId\&quot;: 1,\&quot;id\&quot;: 2,\&quot;title\&quot;: \&quot;Learn WireMock\&quot;, \&quot;completed\&quot;: true}]&quot;))
        );
        
        // ... controller invocation using the WebTestClient
      }
}

</code></pre>
<p>Postman console error:
<img src=""https://i.stack.imgur.com/MhEgU.png"" alt=""Postman console error"" />
Eclipse Console error:
<img src=""https://i.stack.imgur.com/ggDNV.png"" alt=""Eclipse Console error"" /></p>
",https://stackoverflow.com/questions/76193384/wiremock-integration-with-spring-boot-is-throwing-404-exception-as-request-did,"['java', 'spring-boot', 'integration-testing', 'wiremock']",289,False,2,2
"Is this functinal testing, E2E testing, or Integration testing?","<p>What can we call the testing described below?
Integration testing, functional testing, or E2E testing?</p>
<p>It's a set of tests that call the server's APIs to simulate the user's workflow. This test uses real server components, such as running PostgreSQL, Redis, and ElasticSearch using Docker Compose. However, this test doesn't cover the client's behavior.</p>
<p>I've seen this kind of test many times, and some say it's functional testing, while others say it's E2E testing.</p>
<p>In the sense that it simulates the user's workflow, we can call it E2E testing. However, since it doesn't cover the client's (UI) behavior, some say it's not E2E testing.</p>
<p>So is it functional testing? But some say functional testing focuses on one product function. In that sense, it's not functional testing as it covers multiple product functions to follow the user's workflow.
Then, is the safest way to call this just integration testing?</p>
",https://stackoverflow.com/questions/76274380/is-this-functinal-testing-e2e-testing-or-integration-testing,['testing'],21,False,0,0
Mocking protobuf response,"<p>One of our clients uses protobuf format. And I am trying to mock a protobuf response for automating integration testing.
I tried using <a href=""https://github.com/Adven27/grpc-wiremock"" rel=""nofollow noreferrer"">grpc-wiremock</a>. However, this is rpc based, basically wrapped by grpc. Would this tool work for a plain protobuf response mocking? Is there a tool/example how this can be done?</p>
",https://stackoverflow.com/questions/75871749/mocking-protobuf-response,"['mocking', 'protocol-buffers', 'wiremock', 'protobuf-java']",104,False,0,0
How to get response body from MockMvc post request test,"<p>While integration testing of my controller, I am not able to verify the response from a MockMvc post request.
Below are my controller, service and test classes.</p>
<p>StudentController</p>
<pre><code>@RestController
public class StudentController {

    @Autowired
    StudentService studentService;

    @PostMapping(&quot;/add-student&quot;)
    public ResponseEntity&lt;Student&gt; addStudent(@RequestBody Student student) {
        return new ResponseEntity&lt;&gt;(studentService.addStudent(student), HttpStatus.CREATED);
    }
}
</code></pre>
<p>StudentService</p>
<pre><code>@Service
public class StudentService {
    public Student addStudent(Student student) {
        return student;
    }
}
</code></pre>
<p>Student</p>
<pre><code>public class Student {
    String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return &quot;Student{&quot; +
                &quot;name='&quot; + name + '\'' +
                '}';
    }
}
</code></pre>
<p>StudentControllerTest</p>
<pre><code>@WebMvcTest
class StudentControllerTest {

    @Autowired
    MockMvc mockMvc;

    @InjectMocks
    StudentController studentController;

    @Autowired
    ObjectMapper objectMapper;

    @MockBean
    private StudentService studentService;

    @Test
    void addStudent() throws Exception {

        Student student = new Student();
        student.setName(&quot;pushpak&quot;);

        Mockito.when(studentService.addStudent(student)).thenReturn(student);

        MockHttpServletResponse response = mockMvc
                .perform(post(&quot;/add-student&quot;)
                        .content(objectMapper.writeValueAsString(student))
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON)
                ).andReturn().getResponse();
        Assertions.assertEquals(student.getName(), objectMapper.readValue(response.getContentAsString(), Student.class).getName());
    }
}
</code></pre>
<p>I want to get Student object from the test and then compare it with my desired object. But I am not getting any body in the MockHttpServletResponse.</p>
<pre><code>MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /add-student
       Parameters = {}
          Headers = [Content-Type:&quot;application/json;charset=UTF-8&quot;, Accept:&quot;application/json&quot;, Content-Length:&quot;18&quot;]
             Body = {&quot;name&quot;:&quot;pushpak&quot;}
    Session Attrs = {}

Handler:
             Type = com.myapp.spring_boot_test.controller.StudentController
           Method = com.myapp.spring_boot_test.controller.StudentController#addStudent(Student)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

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

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
 at [Source: (String)&quot;&quot;; line: 1, column: 0]

    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
    at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4821)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4723)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3677)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3645)
    at com.myapp.spring_boot_test.controller.StudentControllerTest.addStudent(StudentControllerTest.java:48)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)


Process finished with exit code -1
</code></pre>
",https://stackoverflow.com/questions/75770258/how-to-get-response-body-from-mockmvc-post-request-test,"['java', 'spring', 'spring-boot', 'mockito', 'junit5']",134,True,0,1
issue with generating a document using springdoc-openapi-maven-plugin during the build process of the project,"<p>I'm using the springdoc-openapi-maven-plugin to generate a document_name.json file during the mvn clean install command, with the following plugin configuration:</p>
<pre><code> &lt;plugin&gt;
    &lt;groupId&gt;org.springdoc&lt;/groupId&gt;
    &lt;artifactId&gt;springdoc-openapi-maven-plugin&lt;/artifactId&gt;
    &lt;version&gt;0.2&lt;/version&gt;
    &lt;executions&gt;
        &lt;execution&gt;
            &lt;phase&gt;integration-test&lt;/phase&gt;
            &lt;goals&gt;
                &lt;goal&gt;generate&lt;/goal&gt;
            &lt;/goals&gt;
        &lt;/execution&gt;
    &lt;/executions&gt;
    &lt;configuration&gt; 
        &lt;outputFileName&gt;sentinel-openapi.json&lt;/outputFileName&gt; 
        &lt;outputDir&gt;${project.build.directory/../../openapi-doc/}&lt;/outputDir&gt; 
    &lt;/configuration&gt;
    &lt;/plugin&gt;
</code></pre>
<p>In addition, I'm using the <code>spring-boot-maven-plugin</code> to start and stop the application during integration testing:</p>
<pre><code> &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;pre-integration-test&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;start&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;post-integration-test&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;stop&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
</code></pre>
<p>However, I need to generate the same <code>document_name.json</code> file using the <code>./mvnw package</code> command instead. How can I configure the <code>springdoc-openapi-maven-plugin</code> and <code>spring-boot-maven-plugin</code> to achieve this?</p>
",https://stackoverflow.com/questions/75662193/issue-with-generating-a-document-using-springdoc-openapi-maven-plugin-during-the,"['java', 'spring-boot', 'springdoc-openapi-maven-plugin']",161,False,0,0
How to aggregate Unit testing and Integration test coverage result,"<pre><code>gradle-check:
  ...
  script:
    - ./gradlew check --console=plain ${GRADLE_CHECK_OPTS}
  after_script:
    - mkdir build/reports/tests/ut/
    - mv build/reports/tests/test/* build/reports/tests/ut/
  artifacts:
    when: always
    expire_in: 1 week
    reports:
      junit: build/test-results/test/**/TEST-*.xml
    paths:
      - build/reports/jacocoHtml/
      - build/reports/tests/ut/

integration-test:
  ...
  script:
    - ./gradlew test -Dtest.profile=integration --tests &quot;com.test.integrationtest.*&quot;
    - cat build/reports/jacocoHtml/index.html
  coverage: '/Total.*?([0-9]{1,3})%/'
  after_script:
    - mkdir build/reports/tests/it/
    - mv build/reports/tests/test/* build/reports/tests/it/
  artifacts:
    when: always
    expire_in: 1 week
    reports:
      junit: build/test-results/test/**/TEST-*.xml
    paths:
      - build/reports/jacocoHtml/
      - build/reports/tests/it/

pages:
  stage: pages
  dependencies:
    - gradle-check
    - integration-test
  script:
    - mkdir -p public
    - mv build/reports/tests/ut/ public/
    - mv build/reports/tests/it/ public/
    - mv build/reports/jacocoHtml/ public/
  artifacts:
    paths:
      - public
    expire_in: 100 yrs
  when: always
  ....
</code></pre>
<p>I wanted aggregation between Unit Testing &amp; Integration Testing coverage,
I can see only unit testing coverage is generated in gitlab pipeline,<br />
And integration test coverage is not getting generated in pipeline.</p>
<p>gradle.build file below</p>
<pre><code>def jacocoTestExclude = [
        'com/test/constants/**',
        'com/test/model/**',
]
jacocoTestReport {
    reports {
        xml.enabled false
        csv.enabled false
        html.enabled true
        html.destination file(&quot;${buildDir}/reports/jacocoHtml&quot;)
    }
    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: jacocoTestExclude
            )
        }))
    }
}

jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = 0.0
            }

            failOnViolation true
        }
    }

    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: 'jacocoExclude'
            )
        }))
    }
}

jacoco {
    toolVersion = &quot;0.8.7&quot;
}

test {
    testLogging {
        showStandardStreams = true
        exceptionFormat = 'full'
    }
    if (System.properties['test.profile'] != 'integration') {
        exclude '**/*integrationtest*'
    }
}

check.dependsOn jacocoTestCoverageVerification
jacocoTestCoverageVerification.dependsOn jacocoTestReport
</code></pre>
<p>Since integration test class is not required to run with unit test I have excluded that in test().
jacocoTestCoverageVerification doesn't have any exclusion, some dummy string it is</p>
",https://stackoverflow.com/questions/76109843/how-to-aggregate-unit-testing-and-integration-test-coverage-result,"['gitlab-ci', 'code-coverage', 'jacoco', 'test-coverage']",74,False,0,0
OkHttp3 java.io.IOException: unexpected end of stream on http://localhost:6000 in Jenkins pipeline,"<p>I was facing the below shown error from OkHttp3 in Jenkins Pipeline. I tried the few ways that other post suggest but there is no luck. I was not facing this issue when working locally but only in Jenkins.</p>
<p>I was actually doing integration testing. So the server will be the containers from <code>docker-compose.yml</code> file.</p>
<p>Can someone please help me resolve this issue.</p>
<p>Error:</p>
<pre><code>&lt;java.io.IOException: unexpected end of stream on http://localhost:6000/...&gt;
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
</code></pre>
<p>Client Builder:</p>
<pre><code>List&lt;Protocol&gt; protocols = new ArrayList&lt;Protocol&gt;();
protocols.add(Protocol.HTTP_1_1);
client = new OkHttpClient.Builder()
        .protocols(protocols)
        .readTimeout(120, TimeUnit.SECONDS)
        .connectTimeout(120, TimeUnit.SECONDS)
        .writeTimeout(120, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .build();
</code></pre>
<p>Request Builder:</p>
<pre><code>String baseUrl = &quot;http://localhost:6000/sender&quot;;
Request request = new Request.Builder()
         .url(baseUrl)
         .headers(headers)
         .header(&quot;accept&quot;, &quot;application/json&quot;)
         .header(&quot;Connection&quot;, &quot;close&quot;)
         .header(&quot;Cache-Control&quot;, &quot;no-cache&quot;)
         .header(&quot;Content-Type&quot;, &quot;application/json&quot;)
         .post(RequestBody.create(MediaType.parse(&quot;application/json&quot;), payLoad))
         .build();
Call call = client.newCall(request);
return call.execute();
</code></pre>
<p>OkHttp3 version: <code>3.14.9</code></p>
",https://stackoverflow.com/questions/75702932/okhttp3-java-io-ioexception-unexpected-end-of-stream-on-http-localhost6000-i,"['java', 'spring-boot', 'jenkins', 'jenkins-pipeline', 'okhttp']",103,False,1,0
Automatic testing of upgraded projects,"<p>I upgraded my project from asp core 3.1 to asp core 7</p>
<p>Assuming no tests are currently written for the project</p>
<p>1- how do I know if the code returns the same result as before?</p>
<p>2- Is integration testing appropriate?</p>
<p>3- Is there an automatic method for testing APIs
(For example, I run two different versions of the project that use the same database and test them separately)</p>
",https://stackoverflow.com/questions/75590185/automatic-testing-of-upgraded-projects,"['asp.net-core', 'automated-tests', 'integration-testing']",21,False,0,0
Right-hand side of &#39;instanceof&#39; is not callable supertest,"<p>I'm making API testing with jest and supertest libraries for integration testing, for the backend I'm using Node.js and MongoDB to create/update/delete/get a books collection. the test with get requests works good but when it comes to a post or a put request I get an error &quot;Right-hand side of 'instanceof' is not callable&quot;.
Here is my code:</p>
<p>controller</p>
<pre><code>const bookServices = require(&quot;../services/services.js&quot;)
const BookModel = require('../model/model.js')

const updateBook = async (req, res) =&gt; {
    const {id} = req.params
    if(!id) {
    return res.status(404).json({message: &quot;this book doesn't exist&quot;})
    }
    const updatedObject = await bookServices.updateBook(id, req.body)
    res.json(await bookServices.getBook(id))
}

module.exports = {updateBook}
</code></pre>
<p>Service</p>
<pre><code>const BookModel = require('../model/model.js')

const updateBook = (id, data) =&gt; {
return BookModel.findByIdAndUpdate(id, data)
}

module.exports = { updateBook}
</code></pre>
<p>Route</p>
<pre><code>const express = require(&quot;express&quot;)
const { updateBook} = require('../controller/bookController')
const routes = express.Router()

routes.put(&quot;/updateBook/:id&quot;, updateBook)

module.exports = routes
</code></pre>
<p>Model</p>
<pre><code>const mongoose = require (&quot;mongoose&quot;)
const {Schema, model} = mongoose

const BookSchema = new Schema(
{
    title: {
        type: String,
        require: true
    },
    description: String,
    price: {
        type: Number,
        default: 0
    }
}, { collection : 'Book' })

const BookModel = model(&quot;Book&quot;, BookSchema )

module.exports = BookModel
</code></pre>
<p>Test file</p>
<pre><code>const server = require('./server.js')
const mongoose= require('./dataBaseConfig.js')
const request = require('supertest')

describe(&quot;update book&quot; , () =&gt; {
    it(&quot;should update the book's title&quot;, async ()=&gt; {
    const {id} = await bookServices.createBook({title: &quot;Harry Potter&quot;})
    const res = await request(server).put(`/api/updateBook/${id}`)
    .send({title: &quot;the master and Margarita&quot;})
    expect(res.body).toMatchObject({title: &quot;The master and Margarita&quot;})
    }
    )
})
</code></pre>
",https://stackoverflow.com/questions/76137238/right-hand-side-of-instanceof-is-not-callable-supertest,"['node.js', 'testing', 'jestjs', 'supertest']",29,False,0,0
How to unit test Sealed classes,"<p>I'm struggling with the unit testing of a method that has been tested thru integration testing. The thing, is that this method explicitly calls a <code>sealed</code> class, hence making it unmockable via Moq.</p>
<pre><code>public async Task&lt;DatabaseSymbol&gt; ConnectAndReturnDatabaseSchema(
    string environment,
    string cluster
)
{
    KustoConnectionStringBuilder connection = null;
    if (environment == &quot;LOCAL&quot;)
    {
        connection = new KustoConnectionStringBuilder(
            cluster,
            &quot;AXA&quot;
        ).WithAadAzCliAuthentication(false);
    }
    else
    {
        //TODO: Manage other environments
    }
    ...
}
    
</code></pre>
<p><code>KustoConnectionStringBuilder</code> is a sealed class, with no interfacing, and only a single parent class. I know solutions like <em>JustMock</em> or <em>TypeMock</em> provide solutions, but I'm not paying for a testing library. What's the best way to proceed using Moq (or another free testing library?)</p>
",https://stackoverflow.com/questions/75207756/how-to-unit-test-sealed-classes,"['c#', 'unit-testing', 'moq']",320,True,1,2
SpringBootTest - classes - Mock a required constructor argument,"<p>We are using SpringBootTest for Integration testing.</p>
<p>Let us say for example that we have a class :
ClassWithManyConstructorArgs with one Required Constructor Argument (another class, DependencyA) and no default constructor.</p>
<p>Example :
public ClassWithManyConstructorArgs(DependencyA a){
}</p>
<p>Our Integration test is configured as :</p>
<p>@SpringBootTest (
classes = [ClassWithManyConstructorArgs::class]
)</p>
<p>I need to provide mocked implementations of the DependencyA class. How can I do that?
What is the syntax to tell the system to initialize the ClassWithManyConstructorArgs using mocked DependencyA object?</p>
",https://stackoverflow.com/questions/75839453/springboottest-classes-mock-a-required-constructor-argument,"['spring-boot', 'mockito', 'spring-boot-test']",44,True,1,2
Does WireMock support Mocking GraphQL APIs,"<p>We have multiple micro services which is based on GrapQL and few of them based on REST and each micro service will call multiple other microservices (Java, Spring Boot tech stack).
Now we want to write integration testing for this kind of orchestration.</p>
<p>We thought of using WireMock for Stubbing external Micro Services. But does it support GraphQL? As Wirmock will will support REST MS mocking can it be used for Stubbing GraphQL as well when using with Spring Boot?</p>
",https://stackoverflow.com/questions/75640205/does-wiremock-support-mocking-graphql-apis,"['graphql', 'wiremock', 'spring-cloud-contract', 'spring-graphql']",487,True,2,1
Testing google authentication using mocha and chai,"<p>So, i am a beginner in (like literally just started) unit and integration testing using mocha and chain for backend, i want to test a feature where we create new user, and the new user is created by signing-in with google. How to test the google authentication?
Earlier i thought of triggering <code>/google/callback</code> endpoint directly, but, turns-out, it is only supposed to get response from Google Authentication server.</p>
<p>So, how can i test google authentication using <code>mocha</code> and <code>chai</code>?</p>
<p>Please help!</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/75451944/testing-google-authentication-using-mocha-and-chai,"['unit-testing', 'mocha.js', 'integration-testing', 'chai']",28,False,0,0
How Do I Use The Pre-Deploy AWS CDK Hook?,"<p><strong>Use-Case</strong>:</p>
<p>To run the tests before the <code>CLI</code> deploys the changed resources.</p>
<p>I've seen this <code>preDeploy</code> hook available in the AWS CDK <a href=""https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_cloud-assembly-schema.Hooks.html"" rel=""nofollow noreferrer"">documentation</a>.</p>
<pre class=""lang-js prettyprint-override""><code>// The code below shows an example of how to instantiate this type.
// The values are placeholders you should change.
import * as cloud_assembly_schema from '@aws-cdk/cloud-assembly-schema';
const hooks: cloud_assembly_schema.Hooks = {
  postDeploy: ['postDeploy'],
  postDestroy: ['postDestroy'],
  preDeploy: ['preDeploy'],
  preDestroy: ['preDestroy'],
};
</code></pre>
<p>However, I am unsure how to use it. I've also seen, <a href=""https://docs.aws.amazon.com/cdk/api/v2/docs/integ-tests-alpha-readme.html"" rel=""nofollow noreferrer"">integration testing</a> and the <a href=""https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_integ-tests-alpha.IntegTest.html"" rel=""nofollow noreferrer"">IntegTest construct</a> from which I've been told can work together.</p>
<p><strong>Example:</strong></p>
<p>I have this test which tests to see whether all the <code>lambdaProperties</code> have a <code>key</code> of <code>Code</code>.</p>
<pre class=""lang-js prettyprint-override""><code>it(&quot;Code&quot;, () =&gt; lambdaProperties.forEach(el =&gt; expect(el[&quot;Code&quot;]).toBeDefined()));
</code></pre>
<p><strong>Requirements:</strong></p>
<ol>
<li>User types <code>cdk deploy</code> in the <code>CLI</code></li>
<li>All the tests run</li>
<li>If the tests pass, <code>cdk deploy</code> can happen. Else, it does not continue.</li>
</ol>
",https://stackoverflow.com/questions/75652614/how-do-i-use-the-pre-deploy-aws-cdk-hook,"['testing', 'aws-cdk']",215,True,0,1
How to convert gradle dependencies to maven in Spring Boot?,"<p>I am trying to create an Integration Test, but as the example is created for Gradle, I tried to add them as dependency, but could not make it work.</p>
<p>So, how can I translate the following gradle (with dependencies and any other needed parts) ? I look at on the web, but could not find any tool, etc :(</p>
<p>Note: The GitHub link of the example is on <a href=""https://github.com/arhohuttunen/spring-boot-test-examples/blob/main/spring-boot-integration-testing/build.gradle"" rel=""nofollow noreferrer"">https://github.com/arhohuttunen/spring-boot-test-examples/blob/main/spring-boot-integration-testing/build.gradle</a></p>
<pre><code>
plugins {
    id 'org.springframework.boot' version '3.0.4'
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
}

group = 'com.arhohuttunen'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
targetCompatibility = '17'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.javamoney:moneta:1.4.2'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'org.flywaydb:flyway-core'
    runtimeOnly 'com.h2database:h2'
    runtimeOnly 'org.postgresql:postgresql'
    annotationProcessor 'org.projectlombok:lombok'
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
    testImplementation 'com.squareup.okhttp3:mockwebserver:4.10.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.testcontainers:junit-jupiter'
    testImplementation 'org.testcontainers:postgresql'
    testRuntimeOnly 'com.squareup.okhttp3:okhttp:4.10.0'
}

dependencyManagement {
    imports {
        mavenBom &quot;org.testcontainers:testcontainers-bom:1.17.6&quot;
    }
}

test {
    useJUnitPlatform()
}
</code></pre>
",https://stackoverflow.com/questions/75787145/how-to-convert-gradle-dependencies-to-maven-in-spring-boot,"['java', 'spring-boot', 'maven', 'gradle', 'integration-testing']",102,False,0,1
How to access provider values in integration test with Consumer?,"<p>I am using provider package and I moved my whole logic of class to provider.</p>
<p>I used Consumer:</p>
<pre><code>Consumer3&lt;NewLocationProvider, ListProvider, NewFilterProvider&gt;(
            builder: (context, newLocationProvider, listProvider,newFilterProvider, child) {
                   // class code
            }
</code></pre>
<p>and everything working fine, but when I want to test functionalites from this class in integration testing I can't access values from these providers.</p>
<p>Here is what I did in my integration test:</p>
<pre><code>class MockBuildContext extends Mock implements BuildContext {}

late MockBuildContext _mockContext;


 setUp(() async {
   _mockContext = MockBuildContext();
 });
</code></pre>
<pre><code>await tester.pumpWidget(
          LocalizationsInjector(
            child: MultiProvider(
              providers: [
                ChangeNotifierProvider&lt;NewFilterProvider&gt;(
                    create: (_) =&gt; NewFilterProvider())
              ],
                child: MainNavigator()
            ),
          )
      );
      
</code></pre>
<p>and when I call provider this way:</p>
<pre><code>      print(Provider.of&lt;NewFilterProvider&gt;(_mockContext, listen: false).selectedTagsWithCategories);
</code></pre>
<p>I am getting null and this error:</p>
<pre><code>The following _CastError was thrown running a test:
Null check operator used on a null value
</code></pre>
<p>So my question is how to access this values with this approach in class code?</p>
",https://stackoverflow.com/questions/76172556/how-to-access-provider-values-in-integration-test-with-consumer,"['flutter', 'flutter-provider']",17,False,0,0
pytest overrides existing warning filters,"<p>It seems that ignoring warnings using <code>warnings.filterwarnings</code> is not respected by <code>pytest</code>. For example:</p>
<pre><code>$ cat test.py
import warnings

warnings.filterwarnings('ignore', category=UserWarning)


def test_warnings_filter():
    warnings.warn(&quot;This is a warning&quot;, category=UserWarning)
</code></pre>
<p>When I run this I expect that my explicitly ignored warning will by ignored by <code>pytest</code>. Instead I get this:</p>
<pre><code>$ pytest test.py
=============================================================================== test session starts ===============================================================================
platform darwin -- Python 3.10.8, pytest-7.2.1, pluggy-1.0.0
rootdir: /Users/aldcroft/tmp/pytest
plugins: anyio-3.6.2
collected 1 item                                                                                                                                                                  

test.py .                                                                                                                                                                   [100%]

================================================================================ warnings summary =================================================================================
test.py::test_warnings_filter
  /Users/aldcroft/tmp/pytest/test.py:7: UserWarning: This is a warning
    warnings.warn(&quot;This is a warning&quot;, category=UserWarning)

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
========================================================================== 1 passed, 1 warning in 0.01s ===========================================================================
</code></pre>
<p>I know about <code>pytest.ini</code> config file and the <code>-W</code> flag and <code>@pytest.mark.filterwarnings</code>, but these don't work well
for my use case of integration testing a large number of installed packages via <code>&lt;pkg_name&gt;.test()</code>, where there
are at least a dozen 3rd party warnings that need to be ignored for a clean output.</p>
<p>Any ideas on how to make this work?</p>
",https://stackoverflow.com/questions/75345190/pytest-overrides-existing-warning-filters,"['python', 'pytest', 'warnings']",87,False,2,1
writing tests for react-native integrating RTK Query with Components,"<p>I am using RTK Query Hooks in my expo react native project.Now I am willing to write test for the component contains RTK Query Hook?.</p>
<p>Can Someone else share me the steps how to writing test for integrating RTK Query in react native components.</p>
<p>I tried in google not able to find any reference.</p>
<p>In redux asking to use msw but it is not supporting for react native app.
<a href=""https://redux.js.org/usage/writing-tests#integration-testing-connected-components-and-redux-logic"" rel=""nofollow noreferrer"">https://redux.js.org/usage/writing-tests#integration-testing-connected-components-and-redux-logic</a></p>
<p>I tried with msw/node but it throws an errow not supported</p>
",https://stackoverflow.com/questions/75592480/writing-tests-for-react-native-integrating-rtk-query-with-components,"['react-native', 'redux', 'expo', 'rtk-query']",57,False,1,0
Flutter driver switch to popup window,"<p>I want to automate login functionality for Auth0 on a Flutter web application for integration testing. When I click the login button for Auth0 it opens a pop-up window to enter the cred. Elements in the pop-up are not available to the tester object since they are on a different chrome instance.</p>
<p>Selenium and many other tools support switching to a tab or another window but it seems Flutter driver does not.</p>
<p>Is there a way to enter text in the pop window by using the Flutter driver?</p>
<p><a href=""https://i.stack.imgur.com/sdPvR.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/sdPvR.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75474117/flutter-driver-switch-to-popup-window,"['flutter', 'dart', 'flutter-integration-test']",34,False,0,0
How to use dotnet-coverage connect utility?,"<p>I have a DOTNET ASP.NET API REST service that needs to have integration testing with code coverage measured.</p>
<p>I have the code coverage for unit tests currently functioning.</p>
<p>The testing harness is using Postman (Newman for CLI) issuing requests to an executing instance of the API service.</p>
<p>I was considering using the utility <code>dotnet-coverage connect</code> to collect the code coverage data during testing.  However, I can't find any examples of its usage.</p>
<p>Documentation: <a href=""https://learn.microsoft.com/en-us/dotnet/core/additional-tools/dotnet-coverage#dotnet-coverage-collect"" rel=""nofollow noreferrer"">dotnet-coverage connect</a></p>
<p>Does any one have any experience with this approach? Any other technique I should consider?</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/75211925/how-to-use-dotnet-coverage-connect-utility,"['asp.net', '.net', 'integration-testing', 'code-coverage']",61,False,0,0
Is it possible to do integration testing without mocking the ngrx store?,"<p>My application relies heavily on NgRx store. On startup, large chunks of data are loaded from the backend into the store.</p>
<p>I am trying to define the testing strategy. One option would be integration testing. All what I read says one should mock the store. That seems pretty unreasonable in my case. I wonder whether I should simply initialize the store in beforeAll() and inject the real Store service into the TestBed.</p>
<p>Is there something fundamentally wrong with that idea? Has anyone done it, or a pointer to information on that approach? (I can't find anything in the web)</p>
",https://stackoverflow.com/questions/75302768/is-it-possible-to-do-integration-testing-without-mocking-the-ngrx-store,['angular'],24,False,0,0
What are the tests need to be written in android application?,"<p>I am trying to test Android application for example if I am consuming api calls, what are the tests that need to be done?</p>
<p>I have tried standard assertEquals using JUnit. I also have seen people taking about MockK or Mokito for integration testing. And Espresso for UI testing. I want to know what are the features I should test. If I am going to use JUnit which one do I use? Junit4 or Junit5? What is the difference?
`class ViewModelTest {</p>
<pre><code>@Before
fun setUp() {
}

@After
fun tearDown() {
}

@Test
fun getErrorMessage() {
}

@Test
fun getNewsList() {
}

@Test
fun getLoading() {
}

@Test
fun getJob() {
}

@Test
fun setJob() {
}

@Test
fun getAllNews() {
}`
</code></pre>
<p>This is so fat what I have got generate test cases. Not sure what to do next.</p>
",https://stackoverflow.com/questions/76274495/what-are-the-tests-need-to-be-written-in-android-application,"['android', 'kotlin', 'unit-testing', 'junit', 'mockito']",30,False,-1,0
Python unittest mocking not working as expected,"<p>I got this project structure:</p>
<pre><code>my_project 
├── __init__.py
├── app.py
├── helpers
│   └── __init__.py
└── tests
    ├── __init__.py
    ├── integration
    │   ├── __init__.py
    │   └── test_app.py
    └── unit
        ├── __init__.py
        └── test_helpers.py
</code></pre>
<p>So far, unit testing for <code>helpers</code> hasn't been complicated, i'd patch 3rd parties and some functions within helpers.</p>
<p>The integration testing in <code>tests/integration/test_app.py</code> is being a bit of a blocking point because the patching isn't doing what i need it do to.
For example, I got a method like this:</p>
<p>helpers/<strong>init</strong>.py:</p>
<pre class=""lang-py prettyprint-override""><code>def compute_completeness_metric(
        vendor,
        product,
        fields,
        endpoint):
    body = {&quot;vendor&quot;: vendor, &quot;product&quot;: product, &quot;fields&quot;: fields}
    response_json = requests.post(
        &quot;http://example.com&quot;, json=body)
    if response_json.status_code != 200:
        response_json = &quot;Can't compute&quot;
    else:
        response_json = response_json.json()
    return response_json
</code></pre>
<p>Now, in app.py, I call it the following way:</p>
<pre class=""lang-py prettyprint-override""><code>from helpers import compute_completeness_metric
def main(req: func.HttpRequest) -&gt; func.HttpResponse:
    final_results = {}
    final_results = compute_completeness_metric(vendor, product, fields, endpoint)
...
</code></pre>
<p>And when testing, I try to patch it the following way:</p>
<pre class=""lang-py prettyprint-override""><code>    @patch('data_quality.helpers.compute_completeness_metric')
    def test_app(self, mock_compute_completeness_metric):
      mock_compute_completeness_metric.return_value = &quot;blablabla&quot;
</code></pre>
<p>But the mocked methods do not return what they're supposed to return, instead execute themselves as if they weren't mocked.</p>
<p>Am I missing something? Should I be mocking the methods within <code>get_rule_data_models()</code> ?</p>
<p>TIA!</p>
",https://stackoverflow.com/questions/75158187/python-unittest-mocking-not-working-as-expected,"['python', 'unit-testing', 'integration-testing', 'python-unittest']",47,True,0,1
Testing GCP Cloud Function trigger with PubSub testcontainer,"<p>Is there any way to do integration tests for the Cloud Function using <code>PubSubEmulatorContainer</code>?</p>
<p>My Cloud Function is triggered by the message in the PubSub topic as follows</p>
<pre><code>@Component
@RequiredArgsConstructor
public class MessageIngest implements Consumer&lt;PubSubMessage&gt; {

    private final MessageResource msgResource;
    private final ObjectMapper objectMapper;


    @Override
    public void accept(PubSubMessage pubSubMessage) {
        var message = new String(Base64.getDecoder().decode(pubSubMessage.getData()), UTF_8);
        msgResource.ingest(objectMapper.readValue(message, Message.class));
    }
}
</code></pre>
<p>So far what I found about using <code>PubSubEmulatorContainer</code> for the integration testing is to publish there or subscribe from nothing about how to listen to the topic and trigger the test on publishing to the topic. My assumption is that I need to do that within the <code>contextLoads()</code> test.</p>
<p>For the live code trigger is provided during the deployment as an argument</p>
<pre><code>gcloud functions deploy myCloudFunction --trigger-topic=$TOPIC_TO_LISTEN
</code></pre>
<p>PS.
Provided example from the comments fails for me on testconainers version 1.18.0</p>
<p><code>testSend()</code> errors out as</p>
<pre><code>[ault-executor-0] c.g.c.s.p.c.p.PubSubPublisherTemplate    : Publishing to test-topic topic failed.
com.google.api.gax.rpc.NotFoundException: io.grpc.StatusRuntimeException: NOT_FOUND: Topic not found
com.google.api.gax.rpc.NotFoundException: io.grpc.StatusRuntimeException: NOT_FOUND: Subscription does not exist
</code></pre>
<p>and <code>testWorker()</code> as</p>
<pre><code>[ault-executor-0] c.g.c.s.p.c.p.PubSubPublisherTemplate    : Publishing to test-topic topic failed.
com.google.api.gax.rpc.NotFoundException: io.grpc.StatusRuntimeException: NOT_FOUND: Topic not found
com.google.api.gax.rpc.NotFoundException: com.google.api.gax.rpc.NotFoundException: io.grpc.StatusRuntimeException: NOT_FOUND: Subscription does not exist (resource=test-subscription)
</code></pre>
",https://stackoverflow.com/questions/76272943/testing-gcp-cloud-function-trigger-with-pubsub-testcontainer,"['java', 'spring-boot', 'google-cloud-pubsub', 'testcontainers', 'google-cloud-pubsub-emulator']",71,False,0,1
Wiring real dependencies into Spring Boot integration test,"<p>Spring Boot integration testing here. I have the following service class:</p>
<pre><code>@Service
public class PasswordService implements PasswordEncoder {

    private BCryptPasswordEncoder passwordEncoder;
    private PasswordGenerator passwordGenerator;
    private CharacterCharacteristicsRule passwordCharacteristicsRule;
    private Integer minPasswordLength;

    @Autowired
    public PasswordService(
            BCryptPasswordEncoder passwordEncoder,
            PasswordGenerator passwordGenerator,
            CharacterCharacteristicsRule passwordCharacteristicsRule,
            @Value(&quot;${myapp.users.passwords.min-length}&quot;) Integer minPasswordLength) {
        this.passwordEncoder = passwordEncoder;
        this.passwordGenerator = passwordGenerator;
        this.passwordCharacteristicsRule = passwordCharacteristicsRule;
        this.minPasswordLength = minPasswordLength;
    }

    public String generatePassword() {
        return passwordGenerator.generatePassword(minPasswordLength, passwordCharacteristicsRule.getRules());
    }

    public String protectPassword(String plaintextPassword) {
        return passwordEncoder.encode(plaintextPassword);
    }

    @Override
    public String encode(CharSequence rawPassword) {
        return protectPassword(rawPassword.toString());
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return protectPassword(rawPassword.toString()).equals(encodedPassword);
    }

}
</code></pre>
<p>I have a unit test for each method, but because its <code>generatePassword()</code> method is so important and depends so heavily on its dependencies, I also want to create an integration test for it that actually autowires/injects it with <strong>real</strong> instances of all of its dependencies.</p>
<p>My best attempt:</p>
<pre><code>public class PasswordServiceIT {

    @Inject
    private BCryptPasswordEncoder passwordEncoder;

    @Inject
    private PasswordGenerator passwordGenerator;

    @Inject
    private CharacterCharacteristicsRule passwordCharacteristicsRule;

    private PasswordService passwordService;

    @BeforeEach
    public void setup() {
        passwordService = new PasswordService(passwordEncoder, passwordGenerator, passwordCharacteristicsRule, 10);
    }

    @Test
    public void when_generatePassword_should_generate_valid_password() {

        String password = passwordService.generatePassword();
        System.out.println(String.format(&quot;Password is: %s&quot;, password));

    }


}
</code></pre>
<p>Throws NPEs because <code>passwordEncoder</code> and <code>passwordGenerator</code> are being injected as <code>null</code>. Again I'm looking for the <strong>real</strong> <code>BCryptPasswordEncoder</code> and the <strong>real</strong> <code>PasswordGenerator</code> and the <strong>real</strong> <code>CharacterCharacteristicsRule</code> to be injected into my <code>PasswordService</code> instance here, so I can take it for a <strong>real</strong> test spin.</p>
<p>Can anybody spot where I'm going awry here? Thanks in advance!</p>
",https://stackoverflow.com/questions/75864933/wiring-real-dependencies-into-spring-boot-integration-test,"['spring-boot', 'junit', 'integration-testing']",38,True,0,2
Is there any recommend way to get a ginkgo html report,"<p>I want to use ginkgo as the integration testing tool in project, but I have searched ginkgo doc and github issues below:</p>
<ol>
<li><a href=""https://github.com/onsi/ginkgo/issues/141"" rel=""nofollow noreferrer"">Feature request: HTML reporter #141</a></li>
<li><a href=""https://github.com/onsi/ginkgo/issues/639"" rel=""nofollow noreferrer"">Specs aren't identified in go test . -json output #639</a></li>
</ol>
<p>I find that ginkgo only support json reporter and junit reporter, no html reporter</p>
<p>But it's really need a html report for boss to see the test clearly, so I thought one solution it's to use the ginkgo junit report and use the tool below
<a href=""https://github.com/inorton/junit2html"" rel=""nofollow noreferrer"">https://github.com/inorton/junit2html</a>
transfer it to html report.</p>
<p>It's a solution yet, but I want to know is there have any other solution to get a more beautiful html report. Thanks all.</p>
",https://stackoverflow.com/questions/75042201/is-there-any-recommend-way-to-get-a-ginkgo-html-report,"['html', 'go', 'ginkgo']",128,False,0,0
Flutter Web Test: Set the window size for chrome using flutter drive for integration test,"<p>So I have a project, with some integration testing for flutter web. I want to run these tests inside GitHub Actions. For that, I need to change the window size of chrome while testing, as in the default dimensions, some widgets are overflowing, therefore, getting out of the screen, making them non-interactable. I want to run the browser in 1920x1080 resolution. Currently, I am using the following steps to run it:</p>
<pre><code>chromedriver --port=4444 &amp;
sudo /usr/bin/Xvfb -ac $DISPLAY -screen 0 1920x1080x24 &gt; /dev/null 2&gt;&amp;1 &amp; # optional
</code></pre>
<p>I have already updated the resolution from xvfb, but it did nothing. I also tried adding the following code in the test file itself.</p>
<pre><code>const size = Size(1920, 1080);
await tester.binding.setSurfaceSize(size);
tester.binding.window.physicalSizeTestValue = size;
</code></pre>
<p>But these also did not update the screen size.</p>
<p>For running the tests I am using <code>flutter drive</code> command, like this:</p>
<pre><code>flutter drive --driver=test_driver/integration_test.dart --target=integration_test/test.dart -d chrome --web-renderer=html --headless
</code></pre>
",https://stackoverflow.com/questions/75397725/flutter-web-test-set-the-window-size-for-chrome-using-flutter-drive-for-integra,['flutter'],128,False,0,0
Replace SQLite to LocalDb for unittesting for a ABP.io project,"<p>I am working with ABP and I used the basic setup which is generated by the abp cli with EF Core and SQL Server.</p>
<p>Now, I would like to replace SQLite (the generated one), with a LocalDb database, since I using spatial data for unit- and integration testing.</p>
<p>However, I am not sure how to make the replacement. I have identified the file which initialize the SQLite, and it is reseeded after each unittest.</p>
<p>When switching to LocalDb, I will not flush / seed database, and I think I have solved that out.</p>
<p>This is the generated file <code>...\ABPProject\aspnet-core\ABPProject.EntityFrameworkCore.Tests\EntityFrameworkCore\ABPProjectEntityFrameworkCoreTestModule.cs</code> that uses SQLite, can you please give me an example / ideas how to use LocalDb instead of SQLite?</p>
<pre><code>[DependsOn(
    typeof(ABPProjectEntityFrameworkCoreModule),
    typeof(ABPProjectTestBaseModule),
    typeof(AbpEntityFrameworkCoreSqliteModule)
    )]
public class ABPProjectEntityFrameworkCoreTestModule : AbpModule
{
    private SqliteConnection _sqliteConnection;

    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        ConfigureInMemorySqlite(context.Services);
    }

    private void ConfigureInMemorySqlite(IServiceCollection services)
    {
        _sqliteConnection = CreateDatabaseAndGetConnection();

        services.Configure&lt;AbpDbContextOptions&gt;(options =&gt;
        {
            options.Configure(context =&gt;
            {
                context.DbContextOptions.UseSqlite(_sqliteConnection);
            });
        });
    }

    public override void OnApplicationShutdown(ApplicationShutdownContext context)
    {
        _sqliteConnection.Dispose();
    }

    private static SqliteConnection CreateDatabaseAndGetConnection()
    {
        var connection = new SqliteConnection(&quot;Data Source=:memory:&quot;);
        connection.Open();

        var options = new DbContextOptionsBuilder&lt;ABPProjectDbContext&gt;()
            .UseSqlite(connection)
            .Options;

        using (var context = new ABPProjectDbContext(options))
        {
            context.GetService&lt;IRelationalDatabaseCreator&gt;().CreateTables();
        }

        return connection;
    }
}
</code></pre>
",https://stackoverflow.com/questions/75062553/replace-sqlite-to-localdb-for-unittesting-for-a-abp-io-project,"['entity-framework-core', 'abp']",95,True,0,1
How to understand the meaning of high level requirement and low level requirement in DO-178C?,"<p>DO-178C or DO-178B requires two level software requirements, that is, high-level requirements and low-level requirements.
But generally except the very small software, the hierarchy structure of most embedded software is: (the whole) embedded software -&gt; component -&gt; unit.</p>
<p><a href=""https://i.stack.imgur.com/jF84x.png"" rel=""nofollow noreferrer"">hierarchy structure of embedded software</a></p>
<p>If we develop software requirement for each level, then it will be:<br />
(1) embedded software level requirement: normally this level requirement will be &quot;The embedded software shall xxxx&quot;<br />
(2) component level requirement: normally this level requirement will be &quot;The compoent A shall xxxx&quot;<br />
(3) unit level requirement: normally this level requirement will be &quot;The unit A.1 shall xxxx&quot;<br />
embedded software level requirement is a typical functional requirement which define &quot;what&quot;, while both component level requirement and unit level requirement are &quot;design requirement&quot; which define &quot;how&quot;.</p>
<p>Does the high level requirement of DO-178C covers both embedded software level requirements and component level requirements, and does DO-178C merge these two level requirements into one level?</p>
<p>If they are merged into one level, I feel that there will be some issue because one high level requirement may not be testable in the hardware/software integration testing because that requirement actually define the requirement for one component, and the internal information of that component are not able to be observed during the hardware/software integration testing.</p>
<p>If there are three level software requirements, the tracibiltiy between requiremets and testings is easy for me to understand.<br />
<a href=""https://i.stack.imgur.com/varRG.png"" rel=""nofollow noreferrer"">tracability between three level requirements and tests</a></p>
<p>But if there are only two level requirements, does it mean the traceability will be like as below?<br />
<a href=""https://i.stack.imgur.com/sifhq.png"" rel=""nofollow noreferrer"">tracability between two level requirements and tests</a></p>
",https://stackoverflow.com/questions/75370574/how-to-understand-the-meaning-of-high-level-requirement-and-low-level-requiremen,"['safety-critical', 'requirements-management', 'do178-b']",61,False,0,0
Usage of Config classes in integratiion testing scenario with @SpringJUnitConfig,"<p>I am trying to explore the Spring framework developing a very basic application based on one of my hobbies.
There is a null error when trying to execute a test that i am not really not understanding.</p>
<p>I have a Class tagged as a @Component:</p>
<pre><code>package matchedbetting;

...

@Component(&quot;bet&quot;)
public class Bet {

    private String team1;
    private String team2;

...

    public Bet(String team1, String team2, String league, double bookmaker, double exchange, double commission) {
        super();
        this.team1 = team1;
        this.team2 = team2;
    ...
        this.commission = commission;
    }

    @Autowired
    public Bet() {
        super();
    }

}
</code></pre>
<p>I have a @Configuration class that imports another Configuration for aspects and scans for component in different packages:</p>
<pre><code>package config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({AspectsConfig.class})
@ComponentScan({&quot;matchedbetting&quot;,&quot;utils&quot;})
public class MyTrainingConfig {
    
}
</code></pre>
<p>And in my test package i have a Config class that imports it:</p>
<pre><code>package matchedbetting;

...

import config.MyTrainingConfig;


@Configuration
@Import({MyTrainingConfig.class})
public class MatchedBettingTestConfig {
    
    @Bean MatchedBetting matchedBetting() {
        return new MatchedBettingImpl();
    }
    

}
</code></pre>
<p>Now i run my test and everything looks fine:</p>
<pre><code>package matchedbetting;
...
import org.springframework.context.ConfigurableApplicationContext;

import utils.FieldConsistency;


public class MatchedBettingImplTests {

    private ConfigurableApplicationContext context;
    private Bet bet;
    private FieldConsistency fieldConsistency;
    private MatchedBetting matchedBetting;
    
    @Before
    public void setUp() {
        
        context = SpringApplication.run(MatchedBettingTestConfig.class);

        bet = context.getBean(Bet.class);
        fieldConsistency = context.getBean(FieldConsistency.class);
        matchedBetting = context.getBean(MatchedBetting.class);
        
    }

    @Test
    public void test() {
        
        setTestingBet(bet);
        fieldConsistency.checkTeam(bet);
        System.out.println(&quot;Rating Bet: &quot; + matchedBetting.calculateRating(bet));
        
    }

    private void setTestingBet(Bet bet) {
        bet.setTeam1(&quot;teamA&quot;);
        ...
        bet.setCommission(0.01);
    }
}
</code></pre>
<p>Now i am trying to switch to Spring testing :</p>
<pre><code>package matchedbetting;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import utils.FieldConsistency;

@SpringJUnitConfig(classes=MatchedBettingTestConfig.class)
public class MatchedBettingImplTests {

    @Autowired
    private Bet bet;
    
    @Autowired
    private MatchedBetting matchedBetting;
    
    @Autowired
    private FieldConsistency fieldConsistency;
    


    @Test
    public void test() {
        setTestingBet(bet);
        fieldConsistency.checkTeam(bet);
        System.out.println(&quot;Rating Bet: &quot; + matchedBetting.calculateRating(bet));
        
    }

    private void setTestingBet(Bet bet) {
        bet.setTeam1(&quot;teamA&quot;);
...
        bet.setCommission(0.01);
    }
}

</code></pre>
<p>But the test comes out with the error that &quot;bet&quot; is null. I really don't understand what i am missing.</p>
<pre><code>java.lang.NullPointerException: Cannot invoke &quot;matchedbetting.Bet.setTeam1(String)&quot; because &quot;bet&quot; is null
    at matchedbetting.MatchedBettingImplTests.setTestingBet(MatchedBettingImplTests.java:35)
    at matchedbetting.MatchedBettingImplTests.test(MatchedBettingImplTests.java:28)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:93)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)


</code></pre>
<p>Any thoughts?</p>
<p>Thank you</p>
<p>Trying to switch integration testing using @SpringJUnitConfig</p>
",https://stackoverflow.com/questions/75171441/usage-of-config-classes-in-integratiion-testing-scenario-with-springjunitconfig,"['spring', 'testing', 'spring-test']",107,False,0,1
Junit Mock for AWS Secret manager WebIdentityTokenCredentialsProvider,"<p>I have a AWS secret manager defined in my spring boot configuration to fetch the secrets like below</p>
<pre><code>@Service
public class AWSEnvGateway {
    private static final String REGION = &quot;ap-south-1&quot;;
    @Bean
    AWSSecretsManager getSecretManagerBuilder() {
        return AWSSecretsManagerClientBuilder
                .standard()
                .withCredentials(new WebIdentityTokenCredentialsProvider())
                .withRegion(REGION)
                .build();
    }

    private String getString(String path) {
        //logic to retrieve secret
    }
    
</code></pre>
<p>This above secret manager is working fine as expected and I am able to retrieve the values.</p>
<p>Now issue is, I am facing difficulties while trying to write integration test cases. my test controller class is written as below.</p>
<pre><code>@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = DsiRtApplication.class)
class AccessControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private AccessService accessService;
    @Test
    void getCustomerInfoApiSuccessCase() throws Exception{
        given(accessService.getCustomerInfo(any()))
                .willReturn(ApplicationTestUtils.formCustomerInfoResponseDto());

        //case 1 - only searching with mobile number
        mockMvc.perform(get(&quot;/customer?mobile=OTAwMTkwMDEyMw==&quot;)
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath(&quot;$.responseType&quot;, is(ResponseTemplateDto.ResponseType.SUCCESS.name())));
    }
</code></pre>
<p>When i try to run above test, I am getting error &quot;threw exception with message: You must specify a value for roleArn and roleSessionName&quot;</p>
<p>Based on the above error message, i believe i have to mock the aws secret manager to achieve integration testing. But I am not sure, how to do this. Could someone please help on this.</p>
<p>havent tried any other solutions</p>
",https://stackoverflow.com/questions/75731908/junit-mock-for-aws-secret-manager-webidentitytokencredentialsprovider,"['junit', 'boot', 'aws-secrets-manager']",50,False,0,0
Is it possible to run flutter Web integration tests by means of IntelliJ IDEA?,"<p>After reading the <a href=""https://docs.flutter.dev/cookbook/testing/integration/introduction"" rel=""nofollow noreferrer"">&quot;An introduction to integration testing&quot;</a> article I am able to run my flutter Web integration tests from the command line.
This is all great, but for something more real than the counter app tests we need to debug tests and to be able to run them by means of the IDE. I use IntelliJ IDEA.
When I start the chromedriver, select the &quot;Chrome(web)&quot; in the IntelliJ device selector and trying to run the test by the test file context menu (like any regular unit test) then I see the following message in my console:</p>
<pre><code>Testing started at 17:15 ...
Web devices are not supported for integration tests yet.
</code></pre>
<p>Looks like I can't run these tests like this. Could you guys comment, maybe I miss something.</p>
<p>Also I don't see how I can debug these integration tests for flutter web, maybe you know?</p>
",https://stackoverflow.com/questions/75814128/is-it-possible-to-run-flutter-web-integration-tests-by-means-of-intellij-idea,"['flutter', 'intellij-idea']",39,False,0,0
Do I have to mock Authentication related classes for Integration Tests (@SpringBootTest),"<p>I have the following test class implementations and when I run tests, I get some security related errors (I use Spring Security in my app and tested endpoints requires to be authenticated and authorized).</p>
<p><em><strong>IntegrationTest :</strong></em></p>
<pre><code>@SpringBootTest
@AutoConfigureMockMvc
@Transactional
@ActiveProfiles(&quot;test&quot;)
abstract public class IntegrationTest {

    @Autowired
    protected MockMvc mvc;
}
</code></pre>
<p><em><strong>ProductControllerTest :</strong></em></p>
<pre><code>class ProductControllerTest extends IntegrationTest {

    @Test
    // @Sql(&quot;/insert-data.sql&quot;)
    void findById() throws Exception {
        mvc.perform((get(&quot;/api/v1/products/{id}&quot;, 1)))
                .andExpect(status().isOk())
                .andExpect(jsonPath(&quot;$.data.name&quot;, equalTo(&quot;Laptop&quot;)));
    }

}
</code></pre>
<p>here is my <code>application-test.yml</code> below:</p>
<pre><code>spring:
  datasource:
    url: jdbc:tc:postgresql:13.2-alpine://product

  flyway:
    enabled: true
    placeholderReplacement: false
    baseline-on-migrate: true
</code></pre>
<p>And <code>pom.xml</code>, I think I missed something on pom.xml.
Actually I don't know how can I transforom the original gradle example in here:</p>
<p><a href=""https://github.com/arhohuttunen/spring-boot-test-examples/blob/main/spring-boot-integration-testing/build.gradle"" rel=""nofollow noreferrer"">https://github.com/arhohuttunen/spring-boot-test-examples/blob/main/spring-boot-integration-testing/build.gradle</a></p>
<p>If you check and compare what is missing or redundant, I would really be appreciated.</p>
<pre><code>&lt;!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-configuration-processor&lt;/artifactId&gt;
    &lt;version&gt;3.0.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
    &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
    &lt;version&gt;5.9.2&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.testcontainers/postgresql --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
    &lt;artifactId&gt;postgresql&lt;/artifactId&gt;
    &lt;version&gt;1.17.6&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.testcontainers/testcontainers-bom --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
    &lt;artifactId&gt;testcontainers-bom&lt;/artifactId&gt;
    &lt;version&gt;1.17.6&lt;/version&gt;
    &lt;type&gt;pom&lt;/type&gt;
&lt;/dependency&gt;
</code></pre>
<p>Any idea what is missing or wrong?</p>
<p>This config throws:</p>
<blockquote>
<p>Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]:
Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:tc:postgresql:13.2-alpine://product</p>
</blockquote>
",https://stackoverflow.com/questions/75788243/do-i-have-to-mock-authentication-related-classes-for-integration-tests-springb,"['java', 'spring-boot', 'maven', 'gradle', 'integration-testing']",33,False,0,0
Flutter screenshots for Frameit,"<p>I am automatically generating screenshots of my Flutter app during integration testing and using Fastlane Frameit to put them in a frame and make them all pretty. This works perfectly well with the iOS version. But for Android I am having issues. The bounds of the Flutter screen do not include the bottom navigation bar.</p>
<p><a href=""https://i.stack.imgur.com/apFUY.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/apFUY.png"" alt=""Flutter screenshot"" /></a></p>
<p>Frameit requires the image size to be 1080x1920 or whatever the device resolution is, but running on a device of that size only yields an image 1080x1857. The extra room is for the navigation bar. Further, the screenshot does not include the status bar at the top, but it's the size that's the major issue because it prevents Frameit from running at all.</p>
<p>Surely this is an issue that people have run into before. How has this been resolved?</p>
",https://stackoverflow.com/questions/75790305/flutter-screenshots-for-frameit,"['android', 'flutter', 'fastlane', 'frameit']",46,False,0,1
Redux testing- asyncthunk not updating redux state,"<p>I am learning React and Redux. I have been trying to do integration testing on a react component, that dispatches an action to fetch data from external API. I have used MSW to mock the fetch request. I have also used a Reusable Test Render Function as in <a href=""https://redux.js.org/usage/writing-tests"" rel=""nofollow noreferrer"">redux documentation</a>. when I custom render the component, I expect the mock data from API to be updated in the state and rendered in another component. So far, I see that the store is not getting updated with data from API. I have checked the MSW api mock. It is returning the value I have provided. Can someone please point me in the right direction.</p>
<p>my test file</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import { screen } from '@testing-library/react';
import renderWithProvider from '../utils/test-util';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import MissionsPage from '../components/missions/MissionsPage';

const missions = [
  {
    id: 'testmission1',
    name: 'test1',
    descriptions: 'test mission',
    isReserved: false,
    wiki: '',
  },
];

export const handlers = [
  rest.get('https://api.spacexdata.com/v3/missions', (req, res, ctx) =&gt; {
    return res(ctx.json(missions));
  }),
];

const server = setupServer(...handlers);

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

test('testing Mission page UI', async () =&gt; {
  const { store } = renderWithProvider(&lt;MissionsPage /&gt;);
  console.log(store.getState().missions);
  const text = screen.getByText('/test mission/i');
  expect(await text.toBeInTheDocument());
});</code></pre>
</div>
</div>
</p>
<p>Component I am trying to render</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import { useDispatch, useSelector } from 'react-redux';
import { useEffect } from 'react';
import MissionsTable from './MissionsTable';
import { fetchMissions } from '../../redux/missions/missionSlice';

const MissionsPage = () =&gt; {
  const dispatch = useDispatch();
  const status = useSelector((state) =&gt; state.missions.toFetch);
  useEffect(() =&gt; {
    if (status) {
      dispatch(fetchMissions());
    }
  }, [status, dispatch]);
  return (
    &lt;MissionsTable /&gt;
  );
};

export default MissionsPage;</code></pre>
</div>
</div>
</p>
<p>my reusable test render function</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React from 'react';
import { render } from '@testing-library/react';
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';
import missionSliceReducer from '../redux/missions/missionSlice';

function renderWithProviders(
  ui,
  {
    preloadedState = {},
    store = configureStore({
      reducer: { missions: missionSliceReducer },
      preloadedState,
    }),
    ...renderOptions
  } = {}
) {
  function Wrapper({ children }) {
    return &lt;Provider store={store}&gt;{children}&lt;/Provider&gt;;
  }

  // Return an object with the store and all of RTL's query functions
  return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
}

export default renderWithProviders;</code></pre>
</div>
</div>
</p>
<p>slice where I have defined the Async thunk.</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const initialState = { missions: [], toFetch: 'true' };

export const fetchMissions = createAsyncThunk('missions/fetchMissions', async () =&gt; {
  const response = await fetch('https://api.spacexdata.com/v3/missions');
  return response.json();
});

const missionSlice = createSlice({
  name: 'missions',
  initialState,
  reducers: {
    bookMission: (state, { payload }) =&gt; {
      const newArr = state.missions.map((misObj) =&gt; {
        if (misObj.id === payload) {
          if (misObj.isReserved === true) {
            return { ...misObj, isReserved: false };
          }
          return { ...misObj, isReserved: true };
        }
        return ({ ...misObj });
      });
      const newState = { ...state };
      return { ...newState, missions: newArr };
    },
  },
  extraReducers(builder) {
    builder.addCase(fetchMissions.fulfilled, (state, action) =&gt; {
      const newState = { ...state };
      const missionList = [];
      action.payload.forEach((misObj) =&gt; {
        missionList.push({
          id: misObj.mission_id,
          name: misObj.mission_name,
          description: misObj.description,
          wiki: misObj.wikipedia,
          isReserved: false,
        });
      });
      newState.missions = missionList;
      newState.toFetch = false;
      return newState;
    });
  },
});

export const { bookMission } = missionSlice.actions;
export default missionSlice.reducer;</code></pre>
</div>
</div>
</p>
<p>this is the error I am getting.</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code> console.log
    { missions: [], toFetch: 'true' }

      at Object.&lt;anonymous&gt; (src/__tests__/missionUI.test.js:31:11)

 FAIL  src/__tests__/missionUI.test.js
  ✕ testing Mission page UI (85 ms)

  ● testing Mission page UI

    TestingLibraryElementError: Unable to find an element with the text: /test mission/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    Ignored nodes: comments, script, style
    &lt;body&gt;
      &lt;div&gt;
        &lt;div&gt;
          &lt;div
            class=""table-responsive-sm""
          &gt;
            &lt;table
              class=""missionTable table table-striped table-bordered table-hover""
            &gt;
              &lt;thead&gt;
                &lt;tr&gt;
                  &lt;th&gt;
                    Mission
                  &lt;/th&gt;
                  &lt;th&gt;
                    Description
                  &lt;/th&gt;
                  &lt;th&gt;
                    Status
                  &lt;/th&gt;
                  &lt;th&gt;
                     
                  &lt;/th&gt;
                &lt;/tr&gt;
              &lt;/thead&gt;
              &lt;tbody /&gt;
            &lt;/table&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/body&gt;

      30 |   const { store } = renderWithProvider(&lt;MissionsPage /&gt;);
      31 |   console.log(store.getState().missions);
    &gt; 32 |   const text = screen.getByText('/test mission/i');
         |                       ^
      33 |   expect(await text.toBeInTheDocument());
      34 | });
      35 |</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/75722433/redux-testing-asyncthunk-not-updating-redux-state,"['reactjs', 'redux', 'jestjs', 'react-testing-library', 'redux-toolkit']",108,False,1,1
How to run tests in series in flutter,"<p>Is it possible to force one or more tests in a test suite to run separately and serially in dart/flutter?</p>
<p>Note: I'm not looking to run a single test via CLI filters. I want to be able to run my full test suite as part of my CI flow.</p>
<h3>Example</h3>
<p>The test runner ava is able to do this in javascript via the <code>serial</code> modifier:</p>
<pre><code>test.serial('passes serially', t =&gt; {
    t.pass();
});
</code></pre>
<p><a href=""https://github.com/avajs/ava/blob/main/docs/01-writing-tests.md#running-tests-serially"" rel=""nofollow noreferrer"">https://github.com/avajs/ava/blob/main/docs/01-writing-tests.md#running-tests-serially</a></p>
<h3>Context</h3>
<p>I'm using a third-party library to communicate and authenticate with my backend server. This library makes use of a singleton to make accessing the current user &quot;easier&quot;. However, it makes integration testing in parallel impossible since the testing process can only mimic a single user at a time, which in turn makes tests interfere with each other.</p>
",https://stackoverflow.com/questions/75348775/how-to-run-tests-in-series-in-flutter,"['flutter', 'dart', 'testing']",106,False,0,1
Semantic understanding of unit and integration tests in Axon-based applications,"<p>As we know Axon has its own tools to implement tests. In documentation we can see example with flights like:</p>
<pre><code>FixtureConfiguration&lt;Flight&gt; fixture = new AggregateTestFixture&lt;&gt;(Flight.class);

@Test
void test() {
    fixture.given(/* historical events */)
        .when(new RegisterArrivalTimeCommand(flightId, newArrivalTime))
        .expectEventsMatching(
            Matchers.exactSequenceOf(
                Matchers.messageWithPayload(
                    Matchers.matches(payload -&gt; {
                        // compare payload with expectations
                    })
                )
            )
        );
}
</code></pre>
<p>So, here we see how Axon's aggregate mock(fixture) is created and we see test with assertion(use of matchers). Previously I didn't work in project which had domain driven design, but in other types of projects we have Junit(allows use to write isolated unit-tests using Java) and tools for integration testing(Rest-assured, Cucumber), which allow us to test whole feature/functionality.</p>
<p>And looking on code in example appeared question - Axon tests can be divided in these 2 groups(unit, integration)? Which tests can be called unit? Those, where we send just one command and check all events which apear after it? Or all the tests will be integrational, when we can write one test on concrete flow with commands and events?</p>
",https://stackoverflow.com/questions/75814171/semantic-understanding-of-unit-and-integration-tests-in-axon-based-applications,"['java', 'spring-boot', 'domain-driven-design', 'axon']",42,False,1,0
How to assembleDist a Gradle&#39;s test suite?,"<p>Suppose I have a basic Java app and there is an additional specific test suite for integration testing (defined in Gradle with <a href=""https://docs.gradle.org/current/userguide/jvm_test_suite_plugin.html#sec:declare_an_additional_test_suite"" rel=""nofollow noreferrer""><code>testing{suites{...}}</code> DSL</a>). I would like to package and distribute this test suite as a standalone self-contained thing with <code>org.junit.platform.console.ConsoleLauncher</code> as a <code>Main-Class</code>, and which will only need a JRE for running.</p>
<p>If you have a basic java-app, Gradle's <code>applcation</code> plugin <a href=""https://docs.gradle.org/current/userguide/application_plugin.html#sec:application_tasks"" rel=""nofollow noreferrer"">provides you a convenient set of tasks</a> to package your <code>src/main</code> code + dependencies into a single tar/zip with <code>bin</code>+<code>libs</code> folders. So, you will get a single self-contained package archived into tar/zip, and you will only need JRE to run it. These tasks are named <code>distTar</code>/<code>distZip</code> for producing <code>tar</code>/<code>zip</code> correspondingly, or there is also an <code>assembleDist</code> to produce both types of archive at once.</p>
<p>How can I create my own <code>distSpecificTestSuite(Tar|Zip)</code> task which will package only the test suite I need + it's dependencies into a single self-contained distributable?</p>
",https://stackoverflow.com/questions/76321793/how-to-assembledist-a-gradles-test-suite,['gradle'],18,True,0,1
The procedure &#39;sys.sp_addlinkedserver&#39; cannot be executed because it is not supported in Azure SQL Edge,"<p>I'm trying to setup a environment to do some integration testing.</p>
<p>The environment I try to emulate contains a cluster of mssql server instances that are configured as one master machine and a couple of linked servers acting as slaves. The script interacting with the databases uses the master to query the slaves.</p>
<p>As my machine is a new mac I have to use following docker image to be able to run on the M chip:
mcr.microsoft.com/azure-sql-edge:latest</p>
<p>I use docker compose to setup 2 databases using the above image.
When trying to create a linked server using sql I get the error:
The procedure 'sys.sp_addlinkedserver' cannot be executed because it is not supported in Azure SQL Edge.</p>
<p>The documentation everywhere does not mention this problem.</p>
<p>Anyone any idea why this is not working or an alternative to the setup I'm trying to achieve?</p>
",https://stackoverflow.com/questions/75788941/the-procedure-sys-sp-addlinkedserver-cannot-be-executed-because-it-is-not-supp,"['sql-server', 'azure', 'docker']",73,False,0,0
C# Integration Tests with SQL Server not returning expected data,"<p>I've been trying to test the delete operation with integration testing (XUnit, Moq, FluentAssertions), but I don't understand why the result is not what I expected.</p>
<p>This is the test:</p>
<pre><code> [Fact]
        public async Task DeleteAsync_DeletesRoleModelByGivenId()
        {
            var fakeRoleModel = new Faker&lt;RoleModel&gt;()
                .RuleFor(r =&gt; r.Id, Guid.NewGuid())
                .RuleFor(r =&gt; r.Name, &quot;Role Deleted&quot;)
                .RuleFor(r =&gt; r.Description, f =&gt; f.Lorem.Paragraph())
                .RuleFor(r =&gt; r.CreatedDate, DateTime.Now)
                .RuleFor(r =&gt; r.UpdatedDate, DateTime.Now)
                .RuleFor(r =&gt; r.Deleted, false)
                .Generate();

            var roleToDelete = await _rolesRepository.CreateAsync(fakeRoleModel);

            var client = _integrationTestFactory.CreateClient();
            var response = await client.DeleteAsync($&quot;/api/roles/{roleToDelete.Id}&quot;);

            response.EnsureSuccessStatusCode();

            var deletedRoleById = await _rolesRepository.GetByIdAsync(roleToDelete.Id);
            deletedRoleById.Deleted.ShouldBeTrue();
        }
</code></pre>
<p>The controller for the roleModel should not delete records from the database, instead it should mark the deleted property as true.</p>
<p>Currently, this test is failing. More specifically, in this line</p>
<pre><code>  deletedRoleById.Deleted.ShouldBeTrue();
</code></pre>
<p>The status we get is OK, and if I check the data using SQL server Management Studio, Deleted has been marked as true.</p>
<p>Why is the query from this line, after the model has been updated:</p>
<pre><code>var deletedRoleById = await _rolesRepository.GetByIdAsync(roleToDelete.Id);
</code></pre>
<p>returning an object that has Deleted = false (Initial value)?.</p>
<p>If remove the previous repository query and another request is sent to the controller to get the role by Id:</p>
<pre><code> var secondClient = _integrationTestFactory.CreateClient();
 var roleModel = await client.GetFromJsonAsync&lt;RoleModel&gt;($&quot;/api/roles/{roleToDelete.Id}&quot;);

 roleModel.Name.ShouldBe(&quot;Role Deleted&quot;);
 roleModel.Deleted.ShouldBe(true);
</code></pre>
<p>The test passed and the deleted property is true as it should be.</p>
<p>This is the RoleModel:</p>
<pre><code> public class RoleModel : BaseRecordModel
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public ICollection&lt;RoleFeatureModel&gt; RoleFeatures { get; set; }
        public ICollection&lt;RoleUserModel&gt; RoleUsers { get; set; }
    }
</code></pre>
<p>This is the DeleteAsync method used in the controller, from the
roleRepository:</p>
<pre><code> public virtual async Task DeleteAsync(Guid id)
 {
      var entity = await GetEntityByIdAsync(id);
      entity.Deleted = true;
      _db.Set&lt;TEntity&gt;().Update(entity);

      await _db.SaveChangesAsync();
 } 
</code></pre>
<p>This is the GetByIdAsync method:</p>
<pre><code>public override async Task&lt;RoleModel&gt; GetByIdAsync(Guid Id)
{
   var roleEntity = await _db.Roles
                         .Include(r =&gt; r.RoleFeatures)
                             .ThenInclude(rf =&gt; rf.Feature)
                         .FirstOrDefaultAsync(r =&gt; r.Id == Id);

   return _mapper.Map&lt;RoleModel&gt;(roleEntity);
}
</code></pre>
<p>Why is this happening?</p>
",https://stackoverflow.com/questions/75450980/c-integration-tests-with-sql-server-not-returning-expected-data,"['c#', 'sql-server', 'xunit']",47,True,1,1
How can I get a VaadinView-@QuarkusTest up and running?,"<p>Assume you have the provided Vaadin view (1) and you want to test it with the @QuarkusTest (2) similar as depicted here (3) but not for Vaadin-on-SpringBoot but for Vaadin-on-Quarkus.</p>
<p>I get a NPE:</p>
<pre><code>Caused by: java.lang.NullPointerException: 
Cannot invoke &quot;io.quarkus.arc.InjectableContext.isActive()&quot; because 
the return value of &quot;com.vaadin.quarkus.context.UIContextWrapper.getContext()&quot; is null
</code></pre>
<p>Questions:</p>
<ul>
<li>Does anyone know how to fix this?</li>
<li>Are Quarkus-Tests of this kind already supported by the vaadin quarkus extension?</li>
<li>Do I have to add a missing test-only-dependency I do not yet know of?</li>
</ul>
<p>Sidenotes:</p>
<ul>
<li>The View and Test had been added to the Quarkus-Vaadin-Sample-CRM provided here: <a href=""https://github.com/mstahv/quarkus-crm.git"" rel=""nofollow noreferrer"">https://github.com/mstahv/quarkus-crm.git</a></li>
<li>The NPE occurs with the original version setting (Vaadin=23.0.1|Quarkus=2.7.4.Final) as well as with an update (Vaadin=23.3.4|Quarkus=2.15.3.Final)</li>
<li>The Vaadin-Quarkus-Template does not (yet) come along with a sample @QuarkusTest.</li>
</ul>
<p>(1)</p>
<pre><code> @UIScoped
 @Route(value = &quot;testshowcase&quot;, layout = MainLayout.class)
 @PageTitle(&quot;Testing showcase&quot;)
 @PermitAll
 public class TestingShowcaseView extends HorizontalLayout {
 
     TextField textFieldInput = new TextField(&quot;Eingabe&quot;);
     TextField textFieldOutput = new TextField(&quot;Ausgabe&quot;);
     Button btnProcess = new Button(&quot;To Upper&quot;);
 
     @Inject
     TestingShowcaseService testingShowcaseService;
 
     @PostConstruct
     public void init() {
 
         btnProcess.addClickListener(e -&gt; {
             textFieldOutput.setValue(testingShowcaseService.toUpper(textFieldInput.getValue()));
         });
 
         VerticalLayout barInput = new VerticalLayout(textFieldInput, btnProcess);
         VerticalLayout barOutput = new VerticalLayout(textFieldOutput);
 
         add(barInput, barOutput);
     }
 }

 @RequestScoped
 public class TestingShowcaseService {
 
    public String toUpper(String whatever) {
        if (whatever == null) {
            return null;
        } else {
            return whatever.toUpperCase();
        }
    }
 }
</code></pre>
<p>(2)</p>
<pre><code> @QuarkusTest
 public class TestingShowcaseViewQuarkusTest {
 
     @Inject
     TestingShowcaseView testingShowcaseView;
 
     @Test
     public void testServiceInteraction() {
         String actualOutput;
 
         actualOutput = testingShowcaseView.textFieldOutput.getValue();
         Assertions.assertNull(actualOutput, &quot;... was '%s'.&quot;.formatted(actualOutput));
 
         testingShowcaseView.btnProcess.click();
 
         actualOutput = testingShowcaseView.textFieldOutput.getValue();
         Assertions.assertEquals(&quot;RubbeldieKatz&quot;, actualOutput);
 
     }
 }   
</code></pre>
<p>(3) [https://vaadin.com/docs/latest/tutorial/unit-and-integration-testing/#creating-and-running-integration-tests-for-more-advanced-ui-logic]</p>
",https://stackoverflow.com/questions/75235199/how-can-i-get-a-vaadinview-quarkustest-up-and-running,"['quarkus', 'vaadin-flow']",33,False,0,0
Can WireMock conditionally change authorization header for integration test?,"<p>I'm doing (learning about) integration testing on my web api.  One of my web api methods calls out to EXTERNAL web service that takes <code>Basic</code> authorization.</p>
<p>So, I've intercepted my external web api call via WireMock with the following code in my <code>WebApplicationFactory&lt;&gt;</code> class:</p>
<pre><code>services.AddHttpClient( 
    $&quot;ExternalApiClient&quot;, 
    httpClient =&gt;
    {
        httpClient.BaseAddress = new Uri( wireMockServer.Url );
        httpClient.DefaultRequestHeaders.Authorization = 
            new AuthenticationHeaderValue( 
                &quot;Basic&quot;, 
                Convert.ToBase64String( Encoding.UTF8.GetBytes( &quot;secret&quot; ) ) 
            );
        httpClient.DefaultRequestHeaders.Add( &quot;Accept&quot;, &quot;*/*&quot; );
    } 
);
</code></pre>
<p>With this, when I test my endpoint which requests its own <code>HttpClient</code> for the external service, it uses the WireMock server and serves up 'known' requests:</p>
<pre><code>using var httpClient = httpClientFactory.CreateClient( &quot;ExternalApiClient&quot; );
</code></pre>
<p>So I would like to write <strong>two</strong> tests:</p>
<ol>
<li>Valid test where everything works.</li>
<li>Invalid test where my <code>Basic</code> authentication password is wrong.</li>
</ol>
<p>I can't think of a clean way to do this.  Is there a WireMock (or integration test strategy) that would allow for this?  I've written a WireMock pattern matcher to successfully do this, but I have to manually run one test or the other based on whether I've put the right password in my <code>AddHttpClient</code> call (I can't run all tests within the project with my solution).</p>
",https://stackoverflow.com/questions/75515896/can-wiremock-conditionally-change-authorization-header-for-integration-test,"['c#', 'integration-testing', 'wiremock', 'minimal-apis']",257,True,0,1
sam local invoke failing in nodejs18.x environment,"<p>A while ago AWS announced that they had released nodejs18 runtime env support for serverless lambda and lambda@edge services.<br />
I tried to upgrade the whole project to node18.x.<br />
There was first some issue with sam which didn't recognize runtime nodejs18.x.<br />
After upgrading the sam-cli to the latest version. It sounds like it looks for some emulation environment which is not out there. even in amazon ecr public registry.</p>
<p>our service prominently depends on integration testing which uses sam local invoke in it.<br />
and sam local invoke returns the following:</p>
<pre><code>Building image.....................
Failed to build Docker Image
NoneType: None
Error: Error building docker image: The command '/bin/sh -c mv /var/rapid/aws-lambda-rie-x86_64 /var/rapid/aws-lambda-rie &amp;&amp; chmod +x /var/rapid/aws-lambda-rie' returned a non-zero code: 1
</code></pre>
<p>Does anyone know any workarounds like a custom dockerfile or similar stuff?</p>
<p><strong>update:</strong>
sounds like there is a nodejs18.x emulation for sam. but still get the same error on sam local invoke.</p>
<p><strong>update2:</strong>
found the issue. I was on a macOS machine and it turned out that I need to declare architecture inside my template file like the following under properties section of serverless lambda conf:</p>
<pre><code>Type: 'AWS::Serverless::Function'
  Properties:
    Architectures:
      - arm64
</code></pre>
",https://stackoverflow.com/questions/75484302/sam-local-invoke-failing-in-nodejs18-x-environment,"['node.js', 'aws-lambda', 'serverless', 'aws-sam-cli']",203,False,0,0
Overriden builtins affect live debugging,"<p>I overrided <code>open</code> function, so that to bypass the file path length limitations in Windows, by providing the <code>\\?\</code> code before each path (no admin privileges to change <code>regedit</code>, and the code is distributable to multiple user, so no system changes are possible). The overriding is being done using the following:</p>
<pre><code>import builtins
_open = builtins.open 
def override(path, *args, **kwargs):
    path += &quot;\\\\?\\&quot;
    return _open(*args,**kwargs)
builtins.open = override
</code></pre>
<p>Everything works as expected, <strong>apart</strong> from my IDE, <code>vscode</code>. For example, during debugging, all the files that open have this prefix, and no checkpoints can be added during runtime after a code pause.</p>
<p>I want to enable the overrides only to be considered by the functions and modules that are called inside my application and not affect the behavior of the IDE. Is something like that feasible?</p>
<h2>Update</h2>
<p>An example of how vscode is affected can be seen when I open a new file from the working directory while in debugging:
<a href=""https://i.stack.imgur.com/9HNNB.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/9HNNB.png"" alt=""enter image description here"" /></a></p>
<p>Another example where open is overriden: during tests, so that the folders are <a href=""https://docs.rackspace.com/support/how-to/bind-mounts-in-linux/#:%7E:text=Bind%20mounts%20in%20Linux%C2%AE,a%20jailed%20user%27s%20home%20directory"" rel=""nofollow noreferrer"">bind-mounted</a> and the files are written to somewhere else, application-wide, not affecting the file system, an operation not supported by non root users. This allows for smoother integration testing.</p>
",https://stackoverflow.com/questions/75882577/overriden-builtins-affect-live-debugging,"['python', 'visual-studio-code', 'overriding', 'built-in']",52,True,1,1
How do I perform integration testing with Azure DevOps Pipelines for monitoring file flow?,"<p>I need some guidance for Integraion Testing with Azure DevOps Pipelines.</p>
<p>I'm totally new to DevOps.</p>
<p>The application I need to test monitor folders for new files, once new files are detected they are loaded and teated and then moved to another folder.
There is more to it like file format checking, treatment parameters loading and checking from a database...</p>
<p>I need to test that files are correctly loaded and treated, by checking the folder move flow and file process steps logged in log files.</p>
<p>Basically all steps we do manually after code modification.</p>
<p>I guess steps would be:</p>
<ul>
<li>clone code</li>
<li>load dependencies</li>
<li>compile</li>
<li>start the programme</li>
<li>move test files in monitored folder</li>
<li>check file presences in folders</li>
<li>check log for keywords</li>
<li>build and save/send repport</li>
</ul>
<p>For what I google, this is integration testing not Unit testing.</p>
<p>I wonder if I can use standard Testing framework (xUnit, NUnit, MSTest... ) or a special framework ?
I found reference about Celenium and Appium but they lok to be targeted towards web app/site testing.</p>
<p>I also see reference to Visual Studio test plarform, but for what I understand look to be for unit testing !?</p>
<p>Any suggestions ?</p>
<p>Thanks and regards</p>
",https://stackoverflow.com/questions/76341854/how-do-i-perform-integration-testing-with-azure-devops-pipelines-for-monitoring,"['testing', 'azure-devops', 'azure-pipelines', 'integration']",18,False,-1,0
Separating Contexts of Spring Boot Applications for Integration Testing,"<p>I need to do integration testing on an ecosystem of spring boot based services. Most of these communicate with each other via REST APIs and use their own databases.
Besides, there is some additional stuff that needs to be done in the test cases: Setting up clients, posting and getting data through the services' APIs, etc.</p>
<p>Of course, I could straightforwardly boot all services as separate applications via Java's ProcessBuilder and pass test-specific configuration as arguments (as single properties or in terms of a test-specific <code>.yml</code>/<code>.properties</code> file). But I was wondering if it is not also possible to just launch all services inside the same process, e.g, via <code>SpringApplicationBuilder</code>.</p>
<p><strong>My central question: Is there any simple way to separate services' contexts from each other?</strong>
I am not familiar with boostrap contexts yet but to me it seems that these are not applicable to Spring Boot but Spring Cloud only?</p>
<p>We use maven, thus the integration test project's <code>pom.xml</code> has depedencies to all services' projects (where the respective <code>Application</code> classes are located in).</p>
<p>My sample test code looks like this:</p>
<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringJUnit4ClassRunner.class)
public class MyTest {

    @Test
    public void Test1() {
        SpringApplicationBuilder service1 = new SpringApplicationBuilder( my.service1.Application.class )
            .properties( &quot;spring.config.location=classpath:/service1.yml&quot; );
        service1.run();

        SpringApplicationBuilder service2 = new SpringApplicationBuilder( my.service2.Application.class )
            .properties( &quot;spring.config.location=classpath:/service2.yml&quot; );
        service2.run();

        // do test stuff...
    }
}
</code></pre>
<p>where each of the <code>Application</code> classes looks like</p>
<pre class=""lang-java prettyprint-override""><code>@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootApplication
@EnableConfigurationProperties
public class Application {
    public static void main( String [] args ) {
        TimeZone.setDefault( TimeZone.getTimeZone( &quot;UTC&quot; ) );
        SpringApplication.run( Application.class, args );
    }
}
</code></pre>
<p>Problem is now that the two services share the same Spring context. Omitting the <code>@RunWith(SpringJUnit4ClassRunner.class)</code> annotation does not change this.</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/75747246/separating-contexts-of-spring-boot-applications-for-integration-testing,"['spring-boot', 'integration-testing', 'spring-context']",46,False,1,0
Using a new PostgreSQLContainer test container for each class in a test suite,"<p>I am new to integration testing and I am trying to run a suite of tests in a spring boot project using PostgreSQLContainers from the Testcontainers library.</p>
<p>The structure of the suite looks like this:</p>
<ul>
<li>Suite
<ul>
<li>@SpringBootTest First Class
<ul>
<li>@Test method</li>
<li>@Test method</li>
<li>etc.</li>
</ul>
</li>
<li>@SpringBootTest Second Class
<ul>
<li>@Test method</li>
<li>@Test method</li>
<li>etc.</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>I want to be able to spin up a new, empty container for each class, fill it with a .sql script, run some tests and tear down the container. The issue I am experiencing is that when I try to make the container for the second class the data from the first class is still in the container and I get sql errors because it's trying to re use primary keys.</p>
<p>I am able to run each class individually and the containers work as expected because they are isolated. As soon as I try to run them together in the suite the data seems like it is persisting between the containers.</p>
<p>The general structure of each class is like this:</p>
<pre><code>@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureTestDatabase
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Testcontainers
public class TestClass1 {
    @Container
    private static PostgreSQLContainer postgresqlContainer = new PostgreSQLContainer()
            .withDatabaseName(&quot;foo&quot;)
            .withUsername(&quot;foo&quot;)
            .withPassword(&quot;secret&quot;);

    @Test
    @Sql(&quot;classpath:sql/script.sql&quot;)
    void testMethod1() {
        ...
    }    
    
    @Test
    void testMethod2() {
        ...
    }
}
</code></pre>
<p>Like I said, I am new to Testcontainers so I am wondering if I am using it wrong or if it is suited to doing these types of suites.</p>
",https://stackoverflow.com/questions/76182664/using-a-new-postgresqlcontainer-test-container-for-each-class-in-a-test-suite,"['java', 'spring-boot', 'spring-boot-test', 'testcontainers-junit5']",37,False,0,0
Can I stop the sub camel route for testing purpose only and start it when required,"<p>I have the following route configured and what it basically does is</p>
<p>When the rebalance method is started it does calls &quot;calculateAdjusts&quot; route, and its main aim is call database and calculate some values, then with that it calls next route which actually applies the newly calculated values in to database.</p>
<pre><code>&lt;route id=&quot;rebalance&quot;&gt;
    &lt;from uri=&quot;direct:rebalance&quot;/&gt;

    &lt;to uri=&quot;direct:calculateAdjusts&quot;/&gt;        
&lt;/route&gt;

&lt;route id=&quot;calculateAdjusts&quot;&gt;
    &lt;from uri=&quot;direct:calculateAdjusts&quot;/&gt;

    &lt;bean ref=&quot;someService&quot; method=&quot;calculateAdjustAndRemoteValuesForAllAccounts&quot;/&gt;

    &lt;to uri=&quot;direct:applyAdjusts&quot;/&gt;
&lt;/route&gt;

&lt;route id=&quot;applyAdjusts&quot;&gt;

    &lt;from uri=&quot;direct:lm.applyAdjusts&quot;/&gt;

    &lt;bean ref=&quot;someService&quot; method=&quot;attemptAdjustsForAllAccounts&quot;/&gt;
&lt;/route&gt;
</code></pre>
<p>for integration testing purpose, i have created one rest endpoint which basically stop and start &quot;applyAdjusts&quot; camel route</p>
<pre><code>&lt;rests xmlns=&quot;http://camel.apache.org/schema/spring&quot;&gt;
    &lt;rest&gt;
        &lt;post uri=&quot;stop-applyAdjusts&quot; id=&quot;stop-applyAdjusts-rest&quot;&gt;
            &lt;!-- A route for stopping the applyAdjusts route --&gt;
            &lt;route&gt;
                &lt;setBody&gt;
                    &lt;simple&gt;${exchange.context.routeController.stopRoute(&quot;applyAdjusts&quot;)}&lt;/simple&gt;
                &lt;/setBody&gt;
            &lt;/route&gt;
        &lt;/post&gt;
    &lt;/rest&gt;
    &lt;rest&gt;
        &lt;post uri=&quot;start-applyAdjusts&quot; id=&quot;start-applyAdjusts-rest&quot;&gt;
            &lt;!-- A route for starting the applyAdjusts route --&gt;
            &lt;route&gt;
                &lt;setBody&gt;
                    &lt;simple&gt;${exchange.context.routeController.startRoute(&quot;applyAdjusts&quot;)}&lt;/simple&gt;
                &lt;/setBody&gt;
            &lt;/route&gt;
        &lt;/post&gt;
    &lt;/rest&gt;
&lt;/rests&gt;
</code></pre>
<p>so testing one senario :-</p>
<ol>
<li>I insert some test data in the db.</li>
<li>stop the route &quot;applyAdjusts&quot;</li>
<li>Start the trigger main route &quot;rebalance&quot; which will call the &quot;calculateAdjusts&quot; route and does the calculation from the test data</li>
<li>now I want to insert some more test data in the db.</li>
<li>now start the &quot;applyAdjusts&quot; route by calling the test rest endpoint</li>
<li>test the data in the database for correctness</li>
</ol>
<p>but when I ran the test, it stopped at step 3 and timedout, I think the reason is &quot;applyAdjusts&quot; i stopped it and &quot;rebalance&quot; route seems to be waiting for that and timedout.</p>
<p>so, is there anyway for testing purpose how I can stop the sub route in between and do something and start it? Any suggestions would be highly appricateable (even if I need to craft the route in a different way is also fine)</p>
",https://stackoverflow.com/questions/75667426/can-i-stop-the-sub-camel-route-for-testing-purpose-only-and-start-it-when-requir,"['apache-camel', 'spring-camel']",30,False,0,0
How to get store in Next.js using Redux Toolkit?,"<p>I am trying to make integration testing of my application using Jest. For this case I need to render component to reach any of queries. But for rendering component I need to wrap it in <code>Porvider</code> to get access for component to the store. Like this</p>
<pre><code>//__tests__/Calculator.test.tsx

import { Calculator } from &quot;@/components&quot;;
import { cleanup, render } from &quot;@testing-library/react&quot;;
import { Provider } from &quot;react-redux&quot;;

afterEach(cleanup);

it(&quot;Check Calculator&quot;, () =&gt; {
  const CalculatorTest: React.FunctionComponent = () =&gt; {
    return (
      &lt;Provider store={}&gt;
        &lt;Calculator&gt;&lt;/Calculator&gt;
      &lt;/Provider&gt;
    );
  };
  const { queryAllByTestId } = render(&lt;CalculatorTest /&gt;);
  expect(queryAllByTestId(&quot;calc-test&quot;)).toBeTruthy();
}); 
</code></pre>
<p>But the problem is I'm using <strong>Next.js</strong>. Because of this I have to use Next-redux-wrapper (link: <a href=""https://github.com/kirill-konshin/next-redux-wrapper"" rel=""nofollow noreferrer"">https://github.com/kirill-konshin/next-redux-wrapper</a> ). As I understand this is made to synchronize store on client side and server side. Anyway for this purpose I use wrapper so to provide store to the whole project I use such a code.
Here's my <code>_app.tsx</code>. The syntax of this code was taken from wrapper documentation.</p>
<pre><code>//pages/_app.tsx

const MyApp: FC&lt;AppProps&gt; = ({ Component, ...rest }) =&gt; {
  const { store, props } = wrapper.useWrappedStore(rest);
  return (
    &lt;Provider store={store}&gt;
      &lt;Head&gt;
        &lt;title&gt;Calculator&lt;/title&gt;
      &lt;/Head&gt;
      &lt;Component {...props.pageProps} /&gt;
    &lt;/Provider&gt;
  );
};

export default MyApp;
</code></pre>
<p>Therefore, as you can see, I only get a store in this line of code.</p>
<pre><code> const { store, props } = wrapper.useWrappedStore(rest);
</code></pre>
<p>And Ihardly can understand how it happens and how to reach store in my test file.</p>
<p>Next, I don't import MyApp anywhere. I think it makes the <strong>Next.js</strong> engine somewhere. I just create an <code>index.tsx</code> file in the <code>pages</code> folder, in which I call the components. Here's what it looks like.</p>
<pre><code>//pages/index.tsx

const Index = () =&gt; {
  return (
    &lt;div className=&quot;root d-flex justify-content-center&quot;&gt;
      &lt;History /&gt;
      &lt;Calculator /&gt;
    &lt;/div&gt;
  );
};

export const getServerSideProps: GetServerSideProps =
  wrapper.getServerSideProps((store) =&gt; async ({ params }) =&gt; {
    await store.dispatch(fetchHistory());
    return {
      props: {},
    };
  });
export default Index;
</code></pre>
<p>For clarity of understanding, I also want to show how my store looks like.</p>
<pre><code>//redux/store.ts

const makeStore = () =&gt;
  configureStore({
    reducer: {
      history: calculatorHistoryReducer,
    },

    devTools: true,
  });

const store = makeStore();

export type RootStore = ReturnType&lt;typeof makeStore&gt;;
export type RootState = ReturnType&lt;RootStore[&quot;getState&quot;]&gt;;
export type AppDispatch = typeof store.dispatch;
export type AppThunk&lt;ReturnType = void&gt; = ThunkAction&lt;
  ReturnType,
  RootState,
  unknown,
  Action&lt;string&gt;
&gt;;
export const useAppDispatch: () =&gt; typeof store.dispatch = useDispatch;

export const wrapper = createWrapper&lt;RootStore&gt;(makeStore);
</code></pre>
<p>Could you please tell me how to properly render a component in Jest dom so that I could test it and access different queries?</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/75338037/how-to-get-store-in-next-js-using-redux-toolkit,"['typescript', 'redux', 'next.js', 'jestjs', 'redux-toolkit']",570,True,0,1
Why is pg_promise_1.default undefined when my code runs under jest?,"<p>I am working on a NestJS service, written in Typescript.
It depends on a first-party NPM package for database access, which depends on the pg-promise NPM page.
The service runs very nicely when invoked with &quot;npm run start&quot; (which runs &quot;nest start&quot;).</p>
<p>But during integration testing (“npm run test:integration” which runs jest), it crashes with:</p>
<p><code>TypeError: (0 , pg_promise_1.default) is not a function</code></p>
<p>That is thrown from a line of code in a constructor in the pgPromise package:</p>
<p><code>this.dbClient = (0, pg_promise_1.default)({ /* code omitted */ })(connectionString)</code></p>
<p>There’s some initialization code in the same file as the constructor, which creates pg_promise_1.default:</p>
<p><code>const pg_promise_1 = __importStar(require(&quot;pg-promise&quot;));</code></p>
<p>When run via “npm run start” this returns an object with a ton of properties on it including the ‘default’ property.  When run via “npm run test:integration” this returns only { __esModule: true } which obviously doesn’t have the ‘default’ property.</p>
<p>(This service also has a set of unit tests, which work well, and are out-of-scope for this question - there's no mocking in this scenario, nor should there be.)</p>
<p>I've tried various settings of the 'module' and 'target' options in tsconfig.json in both the service and the first-party NPM package, with no luck at all. (I don't think the package's configuration should change anyway, since the service runs just fine both locally and in production.)</p>
<p>tsconfig.json for the service:</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;module&quot;: &quot;commonjs&quot;,
    &quot;declaration&quot;: true,
    &quot;removeComments&quot;: true,
    &quot;emitDecoratorMetadata&quot;: true,
    &quot;experimentalDecorators&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;target&quot;: &quot;es2020&quot;,
    &quot;sourceMap&quot;: true,
    &quot;outDir&quot;: &quot;./dist&quot;,
    &quot;baseUrl&quot;: &quot;./&quot;,
    &quot;incremental&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;strictNullChecks&quot;: false,
    &quot;noImplicitAny&quot;: false,
    &quot;strictBindCallApply&quot;: false,
    &quot;forceConsistentCasingInFileNames&quot;: false,
    &quot;noFallthroughCasesInSwitch&quot;: false,
    &quot;allowJs&quot;: true,
    &quot;moduleResolution&quot;: &quot;Node&quot;,
    &quot;resolveJsonModule&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;rootDir&quot;: &quot;.&quot;
  },
  &quot;include&quot;: [&quot;./src/**/*&quot;, &quot;rq&quot;],
  &quot;exclude&quot;: [&quot;./scripts&quot;]
}
</code></pre>
<p>jest.config.js for the integration tests:</p>
<pre><code>module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  modulePaths: ['&lt;rootDir&gt;'],
  modulePathIgnorePatterns: ['./dist/'],
  moduleDirectories: ['node_modules', 'src'],
  testMatch: ['**/src/test/integration/*'],
  testTimeout: 30000,
}

</code></pre>
<p>tsconfig.json for the first-party database module, which wraps pg-promise:</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;es2020&quot;,                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    &quot;lib&quot;: [&quot;es2020&quot;],                                   /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    &quot;module&quot;: &quot;commonjs&quot;,                                /* Specify what module code is generated. */
    &quot;rootDir&quot;: &quot;.&quot;,                                      /* Specify the root folder within your source files. */
    &quot;moduleResolution&quot;: &quot;node&quot;,                          /* Specify how TypeScript looks up a file from a given module specifier. */
    &quot;resolveJsonModule&quot;: true,                           /* Enable importing .json files. */
    &quot;allowJs&quot;: true,                                     /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    &quot;declaration&quot;: true,                                 /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    &quot;sourceMap&quot;: true,                                   /* Create source map files for emitted JavaScript files. */
    &quot;outDir&quot;: &quot;dist&quot;,                                    /* Specify an output folder for all emitted files. */
    &quot;esModuleInterop&quot;: true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    &quot;forceConsistentCasingInFileNames&quot;: true,            /* Ensure that casing is correct in imports. */
    &quot;strict&quot;: true,                                      /* Enable all strict type-checking options. */
    &quot;noImplicitAny&quot;: true,                               /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    &quot;skipLibCheck&quot;: true                                 /* Skip type checking all .d.ts files. */
  },
  &quot;include&quot;: [&quot;./**/*.ts&quot;, &quot;./**/*.json&quot;],
  &quot;exclude&quot;: [&quot;./test&quot;, &quot;./coverage&quot;, &quot;./coverage-int&quot;, &quot;./dist&quot;]
}
</code></pre>
<p>I also tried changing module=commonjs to module=ES2020 in that file, but the integration tests still fail with the same TypeError.</p>
",https://stackoverflow.com/questions/76068609/why-is-pg-promise-1-default-undefined-when-my-code-runs-under-jest,"['typescript', 'jestjs', 'ts-jest', 'pg-promise']",42,False,0,0
Mocking an injectable class for testing that other regular clases depend on,"<p>I have an abstract class <code>DatabaseManager</code>, and an implementation <code>DatabaseManagerImpl</code>, the latter is annotated like this:</p>
<pre class=""lang-dart prettyprint-override""><code>@LazySingleton(as: DatabaseManager)
class DatabaseManagerImpl implements DatabaseManager {
</code></pre>
<p>A lot of other classes then depend on <code>DatabaseManager</code> like this:</p>
<pre class=""lang-dart prettyprint-override""><code>@LazySingleton()
class SomeClass {
  const SomeClass(this._databaseManager);

  final DatabaseManager _databaseManager;
</code></pre>
<p>I'm trying to add integration testing - as in, <a href=""https://en.wikipedia.org/wiki/Integration_testing"" rel=""nofollow noreferrer"">testing multiple modules at the same time</a>, not the one where you run the app on a device. Basically, I'm testing how the backend executes certain features. Most of the backend classes depend on <code>DatabaseManager</code> (it initializes and provides the database connection).</p>
<p>First of all, I want to initialize an in-memory database for testing and fill it with fake values, so I need to mock <code>DatabaseManager</code>. The second reason is that I need to use <code>sqflite_ffi</code> because the tests are run on Linux.</p>
<p>The problem is, I don't know where to put <code>DatabaseManagerMock</code>: under the lib or test folder?</p>
<ol>
<li>if I put it under the <code>test</code> folder (which is where it belongs ideally), I can't generate injectable config for it because it (obviously) doesn't get included into the generated file under <code>lib</code>. I had an idea to generate a second injectable config file for tests and then run them in this order:</li>
</ol>
<pre class=""lang-dart prettyprint-override""><code>await configureDependencies() // from the main project
await configureTestDependencies() // from tests
</code></pre>
<p>But injectable breaks when I do that: it can't generate proper import paths for the test directory.</p>
<ol start=""2"">
<li>Putting <code>DatabaseManagerMock</code> under the lib folder. Since I need <code>sqflite_ffi</code> only for testing, it should be a dev dependency, but that gives a depend_on_referenced_packages warning when I import it to use in <code>DatabaseManagerMock</code>.</li>
</ol>
<hr />
<p>What is the proper way to do this? I think I might be overthinking and there is a completely different approach to this that I'm missing.</p>
",https://stackoverflow.com/questions/75817628/mocking-an-injectable-class-for-testing-that-other-regular-clases-depend-on,"['flutter', 'testing', 'injectable']",34,True,1,1
Use H2 DB for testing in Spring Boot,"<p>I have been working on a demo Spring Boot project that provides a REST API to perform CRUD operations on some entity classes. During the development of this REST API I have also created unit and integration tests to ensure the flows work as expected. During the integration testing phase I thought it would be better to create a separate DB for testing running on a test profile, rather then using the same development one. However, trying to set up the integration tests to use the test DB and perform the CRUD operations against the test DB turned out to be problematic for me.
To be more concrete, here are the properties files and the integration test class that caused issues:</p>
<p>--- src/main/resources/application.properties ---</p>
<pre><code>spring.datasource.url=jdbc:postgresql://localhost:5432/employee-management-system
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:data-dev.sql
</code></pre>
<p>--- src/test/resources/application-test.properties ---</p>
<pre><code>spring.datasource.url=jdbc:h2:mem:employee-management-system-test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.h2.console.enabled=true

spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

logging.level.sql=DEBUG
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:schema-test.sql
</code></pre>
<p>--- EmployeeRestControllerIntegrationTest.java ---</p>
<pre><code>@ActiveProfiles(&quot;test&quot;)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Sql(scripts = {&quot;classpath:data-test.sql&quot;})
class EmployeeRestControllerIntegrationTest {

    @Autowired
    private TestRestTemplate template;

    @Autowired
    private EmployeeRepository employeeRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Spy
    private ModelMapper modelMapper;

    private EmployeeDto employeeDto1;
    private EmployeeDto employeeDto2;
    private List&lt;EmployeeDto&gt; employeeDtos;

    @BeforeEach
    void setUp() {
        employeeDto1 = modelMapper.map(getMockedEmployee1(), EmployeeDto.class);
        employeeDto2 = modelMapper.map(getMockedEmployee2(), EmployeeDto.class);
        employeeDtos = modelMapper.map(getMockedEmployees(), new TypeToken&lt;List&lt;EmployeeDto&gt;&gt;() {}.getType());
    }

    @AfterEach
    void tearDown() {
        employeeRepository.deleteAll();
    }

    @Test
    void getAllEmployees_shouldReturnListOfEmployees() throws Exception {
        ResponseEntity&lt;String&gt; response = template.getForEntity(&quot;/api/employees&quot;, String.class);
        assertNotNull(response);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getHeaders().getContentType()).isEqualTo(APPLICATION_JSON);
        List&lt;EmployeeDto&gt; result = objectMapper.readValue(response.getBody(), new TypeReference&lt;&gt;() {});
        Collections.reverse(employeeDtos);
        assertThat(result).isEqualTo(employeeDtos);
    }

    @Test
    void getEmployeeById_withValidId_shouldReturnEmployeeWithGivenId() {
        ResponseEntity&lt;EmployeeDto&gt; response = template.getForEntity(&quot;/api/employees/1&quot;, EmployeeDto.class);
        assertNotNull(response);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getHeaders().getContentType()).isEqualTo(APPLICATION_JSON);
        assertThat(response.getBody()).isEqualTo(employeeDto1);
    }

    @Test
    void getEmployeeById_withInvalidId_shouldThrowException() {
        Long id = 999L;
        ResponseEntity&lt;String&gt; response = template.getForEntity(&quot;/api/employees/999&quot;, String.class);
        assertNotNull(response);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
        assertThat(response.getHeaders().getContentType()).isEqualTo(APPLICATION_JSON);
        assertThat(response.getBody()).isEqualTo(&quot;Resource not found: &quot; + String.format(EMPLOYEE_NOT_FOUND, id));
    }

    @Test
    void saveEmployee_shouldAddEmployeeToList() {
        ResponseEntity&lt;EmployeeDto&gt; response = template.postForEntity(&quot;/api/employees&quot;, employeeDto1, EmployeeDto.class);
        assertNotNull(response);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        assertThat(response.getHeaders().getContentType()).isEqualTo(APPLICATION_JSON);
        assertThat(response.getBody()).isEqualTo(employeeDto1);
    }

    @Test
    void updateEmployeeById_withValidId_shouldUpdateEmployeeWithGivenId() {
        Long id = 1L;
        EmployeeDto employeeDto = employeeDto2;
        employeeDto.setId(id);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(APPLICATION_JSON);
        ResponseEntity&lt;EmployeeDto&gt; response = template.exchange(&quot;/api/employees/1&quot;, HttpMethod.PUT, new HttpEntity&lt;&gt;(employeeDto2, headers), EmployeeDto.class);
        assertNotNull(response);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getHeaders().getContentType()).isEqualTo(APPLICATION_JSON);
        assertThat(response.getBody()).isEqualTo(employeeDto);
    }

    @Test
    void updateEmployeeById_withInvalidId_shouldThrowException() {
        Long id = 999L;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(APPLICATION_JSON);
        ResponseEntity&lt;String&gt; response = template.exchange(&quot;/api/employees/999&quot;, HttpMethod.PUT, new HttpEntity&lt;&gt;(employeeDto2, headers), String.class);
        assertNotNull(response);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
        assertThat(response.getHeaders().getContentType()).isEqualTo(APPLICATION_JSON);
        assertThat(response.getBody()).isEqualTo(&quot;Resource not found: &quot; + String.format(EMPLOYEE_NOT_FOUND, id));
    }

    @Test
    void deleteEmployeeById_withValidId_shouldRemoveEmployeeWithGivenIdFromList() {
        ResponseEntity&lt;Void&gt; response = template.exchange(&quot;/api/employees/1&quot;, HttpMethod.DELETE, new HttpEntity&lt;&gt;(null), Void.class);
        assertNotNull(response);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
        ResponseEntity&lt;Void&gt; getResponse = template.exchange(&quot;/api/employees/1&quot;, HttpMethod.GET, null, Void.class);
        assertNotNull(getResponse);
        assertThat(getResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
        ResponseEntity&lt;Void&gt; getAllResponse = template.exchange(&quot;/api/employee&quot;, HttpMethod.GET, null, Void.class);
        assertNotNull(getAllResponse);
    }

    @Test
    void deleteEmployeeById_withInvalidId_shouldThrowException() {
        Long id = 999L;
        ResponseEntity&lt;String&gt; response = template.exchange(&quot;/api/employees/999&quot;, HttpMethod.DELETE, new HttpEntity&lt;&gt;(null), String.class);
        assertNotNull(response);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
        assertThat(response.getHeaders().getContentType()).isEqualTo(APPLICATION_JSON);
        assertThat(response.getBody()).isEqualTo(&quot;Resource not found: &quot; + String.format(EMPLOYEE_NOT_FOUND, id));
    }
}
</code></pre>
<p>Indeed when I run the tests:</p>
<ul>
<li>the application context is started</li>
<li>the Tomcat container is initialized to run on a random port</li>
<li>the Hikkari Datasource adds the connection to jdbc:h2:mem:employee-management-system-test</li>
</ul>
<p>Afterwards, the application throws this exception with the following stack trace:</p>
<pre><code>org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #8 of class path resource [data-test.sql]: INSERT INTO employees_experiences(employee_id, experience_id) VALUES (1, 1), (1, 2), (2, 3), (2, 4), (3, 1), (3, 2), (4, 3), (4, 4), (5, 1), (5, 2), (6, 3), (6, 4), (7, 1), (7, 2), (8, 3), (8, 4), (9, 1), (9, 2), (10, 3), (10, 4), (11, 1), (11, 2), (12, 3), (12, 4), (13, 1), (13, 2), (14, 3), (14, 4), (15, 1), (15, 2), (16, 3), (16, 4), (17, 1), (17, 2), (18, 3), (18, 4), (19, 1), (19, 2), (20, 3), (20, 4)com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referential integrity constraint violation: &quot;FK9KRGPGEGMHONO5TCMUS7LBLJY: PUBLIC.EMPLOYEES_EXPERIENCES FOREIGN KEY(EMPLOYEE_ID) REFERENCES PUBLIC.EMPLOYEES(ID) (1)&quot;; SQL statement:
INSERT INTO employees_experiences(employee_id, experience_id) VALUES (1, 1), (1, 2), (2, 3), (2, 4), (3, 1), (3, 2), (4, 3), (4, 4), (5, 1), (5, 2), (6, 3), (6, 4), (7, 1), (7, 2), (8, 3), (8, 4), (9, 1), (9, 2), (10, 3), (10, 4), (11, 1), (11, 2), (12, 3), (12, 4), (13, 1), (13, 2), (14, 3), (14, 4), (15, 1), (15, 2), (16, 3), (16, 4), (17, 1), (17, 2), (18, 3), (18, 4), (19, 1), (19, 2), (20, 3), (20, 4)
</code></pre>
<p>I understand the problem has to do with a foreign key constraint violation in the table employees_experiences (mapping table that was created because the Employee and Experience entities have a many-to-many relationship).
Even so, I don't know what should be done to solve this issue and make the tests pass. Any suggestions or recommendations on how to solve the issues or articles/videos that I should consider would be highly appreciated. Also, please tell me if I should provide more of the project code.</p>
",https://stackoverflow.com/questions/75919090/use-h2-db-for-testing-in-spring-boot,"['sql', 'spring-boot', 'h2', 'spring-test']",194,False,1,0
Reusing Flyway Migrations between SpringBoot Tests (Zonky + Flyway + SpringBoot3),"<p>I've been using Zonky Embedded DB Spring Tests + Flyway Spring Test to do integration testing with in-memory databases built from a collection of SQL migration scripts managed by Flyway.  The issue I'm having is that, as of SpringBoot 3, this configuration is resulting in the Flyway Migrations being reapplied between any tests that alter the SpringBoot Context.  The DB container itself isn't restarted, but the migrations are reapplied.  This is both slowing down test execution and forcing me to re-write the migration scripts to be repeatable.</p>
<p>In SpringBoot 2, this was not the case.  The embedded test DB would be refreshed between tests, but would not re-run migrations.</p>
<p>Is there a way to replicate the behavior from Zonky+Flyway from SpringBoot2, where the migrations would NOT be re-applied between each context dirtying test?</p>
<p>ex.</p>
<p><em><strong>application-test.yaml</strong></em></p>
<pre><code>spring.flyway.mixed: true
spring.flyway.schemas: public,test
zonky.test.database.provider: zonky
zonky.test.database.refresh: never
</code></pre>
<p><em><strong>Example Tests</strong></em></p>
<pre><code>@AutoConfigureEmbeddedDatabase
@SpringBootTest
@ActiveProfiles(&quot;test&quot;)
class DemoApplicationTests {
   
   @Test
   void contextLoads() {
   }
}
</code></pre>
<pre><code>@AutoConfigureEmbeddedDatabase
@SpringBootTest
@ActiveProfiles(&quot;test&quot;)
class DemoApplicationTests2 {
   
   @Test
   void contextLoads() {
   }
}
</code></pre>
<pre><code>@AutoConfigureEmbeddedDatabase
@SpringBootTest
@ActiveProfiles(&quot;test&quot;)
class DemoApplicationTests3 {
   @MockBean RestTemplate restTemplate; //Add a mock that requires the SpringBoot context to be re-created

   @Test
   void contextLoads() {
   }
}
</code></pre>
<p>Originally, when I was running this setup in SpringBoot 2, the DB migrations would be run once, while initializing the context for executing DemoApplicationTests1.  The DB would then be re-used for Test 2 and 3, even though Test3 would re-initialize the SpringBoot Context due to the additional mock.</p>
<p><em><strong>SpringBoot 2 libraries</strong></em></p>
<pre><code>id 'org.springframework.boot' version '2.6.6'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
...
testImplementation 'io.zonky.test:embedded-database-spring-test:2.1.1'
testImplementation 'io.zonky.test:embedded-postgres:1.3.1'
testImplementation 'org.flywaydb:flyway-core:8.3.0'
testImplementation 'org.flywaydb.flyway-test-extensions:flyway-spring-test:7.0.0'
testImplementation enforcedPlatform('io.zonky.test.postgres:embedded-postgres-binaries-bom:12.10.0')
</code></pre>
<p>After updating to SpringBoot3, and migrating to newer, compatible versions of the zonky and flyway libraries, this is behaving differently.  The embedded DB is re-used between Tests 1 and 2, but during the Spring context re-initialization for Test 3, the Flyway migrations are being re-run.</p>
<p><em><strong>SpringBoot 3 libraries</strong></em></p>
<pre><code>id 'org.springframework.boot' version '3.0.1'
id 'io.spring.dependency-management' version '1.1.0'
...
testImplementation 'io.zonky.test:embedded-database-spring-test:2.2.0'
testImplementation 'io.zonky.test:embedded-postgres:2.0.3'
testImplementation 'org.flywaydb:flyway-core:9.15.2'
testImplementation 'org.flywaydb.flyway-test-extensions:flyway-spring-test:7.0.0'
testImplementation enforcedPlatform('io.zonky.test.postgres:embedded-postgres-binaries-bom:12.10.0')
</code></pre>
<p><em><strong>Logs from Test3</strong></em></p>
<pre><code>2023-04-03T11:01:14.557-05:00  INFO 31396 --- [  prefetching-2] o.f.c.i.database.base.BaseDatabaseType   : Database: jdbc:postgresql://localhost:53919/hzukrkxcbfcz (PostgreSQL 12.10)
2023-04-03T11:01:14.618-05:00  INFO 31396 --- [  prefetching-2] o.f.core.internal.command.DbValidate     : Successfully validated 5 migrations (execution time 00:00.019s)
2023-04-03T11:01:14.619-05:00  INFO 31396 --- [  prefetching-2] o.f.core.internal.database.base.Schema   : Creating schema &quot;test&quot; ...
2023-04-03T11:01:14.630-05:00  INFO 31396 --- [  prefetching-2] o.f.c.i.s.JdbcTableSchemaHistory         : Creating Schema History table &quot;public&quot;.&quot;flyway_schema_history&quot; ...
2023-04-03T11:01:14.875-05:00  INFO 31396 --- [  prefetching-2] o.f.core.internal.command.DbMigrate      : Current version of schema &quot;public&quot;: null
2023-04-03T11:01:14.893-05:00  INFO 31396 --- [  prefetching-2] o.f.core.internal.command.DbMigrate      : Migrating schema &quot;public&quot; to version &quot;0 - init&quot;
</code></pre>
",https://stackoverflow.com/questions/75922531/reusing-flyway-migrations-between-springboot-tests-zonky-flyway-springboot3,"['spring-boot', 'flyway']",86,False,1,0
QuarkusTest class cast exception BuildChainBuilder,"<p>I have a Gradle project with a Quarkus application to deploy a RESTful API.</p>
<p>The Gradle project is broken into 2 sub-projects: 'app' and 'spec'.  <code>spec</code> is using the Open API Generator to create the RestEasy Classic (RestEasy Reactive doesn't appear to be available at this taime) interfaces and classes.  <code>app</code> has a dependency on that sub-project.</p>
<p>The 'app' project has several directories/modules:</p>
<ul>
<li>app/src/main</li>
<li>app/src/docker</li>
<li>app/src/test</li>
<li>app/src/componentTest</li>
<li>app/src/smokeTest</li>
<li>app/src/integrationTest</li>
</ul>
<p>Unfortunately, only the unit tests (which are basic JUnit 5 tests) will run successfully (pass/fail).  I receive the following stack trace when attempting to execute the <code>@QuarkusTest</code> annotated tests:</p>
<pre><code>java.lang.ClassCastException: class io.quarkus.builder.BuildChainBuilder cannot be cast to class io.quarkus.builder.BuildChainBuilder (io.quarkus.builder.BuildChainBuilder is in unnamed module of loader io.quarkus.bootstrap.classloading.QuarkusClassLoader @45cff11c; io.quarkus.builder.BuildChainBuilder is in unnamed module of loader 'app')
java.lang.RuntimeException: java.lang.ClassCastException: class io.quarkus.builder.BuildChainBuilder cannot be cast to class io.quarkus.builder.BuildChainBuilder (io.quarkus.builder.BuildChainBuilder is in unnamed module of loader io.quarkus.bootstrap.classloading.QuarkusClassLoader @45cff11c; io.quarkus.builder.BuildChainBuilder is in unnamed module of loader 'app')
    at io.quarkus.test.junit.QuarkusTestExtension.throwBootFailureException(QuarkusTestExtension.java:625)
    at io.quarkus.test.junit.QuarkusTestExtension.interceptTestClassConstructor(QuarkusTestExtension.java:696)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.api.extension.InvocationInterceptor.interceptTestClassConstructor(InvocationInterceptor.java:73)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:62)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestClassConstructor(ClassBasedTestDescriptor.java:363)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateTestClass(ClassBasedTestDescriptor.java:310)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:79)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:286)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:278)
    at java.base/java.util.Optional.orElseGet(Optional.java:364)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:277)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:105)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:104)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:68)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at jdk.proxy1/jdk.proxy1.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: java.lang.ClassCastException: class io.quarkus.builder.BuildChainBuilder cannot be cast to class io.quarkus.builder.BuildChainBuilder (io.quarkus.builder.BuildChainBuilder is in unnamed module of loader io.quarkus.bootstrap.classloading.QuarkusClassLoader @45cff11c; io.quarkus.builder.BuildChainBuilder is in unnamed module of loader 'app')
    at io.quarkus.test.junit.QuarkusTestExtension$TestBuildChainFunction$1.accept(QuarkusTestExtension.java:1257)
    at io.quarkus.deployment.QuarkusAugmentor.run(QuarkusAugmentor.java:130)
    at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:331)
    at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:252)
    at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:60)
    at io.quarkus.test.junit.QuarkusTestExtension.doJavaStart(QuarkusTestExtension.java:222)
    at io.quarkus.test.junit.QuarkusTestExtension.ensureStarted(QuarkusTestExtension.java:592)
    at io.quarkus.test.junit.QuarkusTestExtension.beforeAll(QuarkusTestExtension.java:640)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeBeforeAllCallbacks$12(ClassBasedTestDescriptor.java:395)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeBeforeAllCallbacks(ClassBasedTestDescriptor.java:395)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:211)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:84)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:148)
    ... 52 more
</code></pre>
<p>I thought the Gradle plugin Unbroken Dome TestSets might have been conflicting with the Quarkus platform generated modules <code>integrationTest</code> and <code>test</code>.  After replacing that plugin with basic configuration changes to achieve the same purpose, it still fails at the same point.</p>
<p>Moving the test to a Quarkus test module has no change either.</p>
<p>Not all modules will rely on the Quarkus Testing libraries as I'm aware of challenges mixing them.  For example, the smoke test will only rely on RestAssured to execute liveness/health checks after deploy.  Integration testing could be done with Docker instead of the Qaurkus library.</p>
<p>I would like to use component level testing on the CDI generated beans from Quarkus if I can, for example:</p>
<pre><code>@RequestScoped
public class SomeService {
    @Inject
    DatabaseService databaseService;
}
</code></pre>
<p>In test:</p>
<pre><code>@QuarkusTest
public class ComponentTest {
    @Inject 
    SomeService someService;

    @Test
    void test() {
         //Run tests on someService with injected dependencies
    }

}
</code></pre>
<p>So it all comes down to how to successfully get the component test to run.  Any help is appreciated.</p>
<ul>
<li>Gradle 7.5.1</li>
<li>Java 17</li>
<li>Quarkus 2.16.0.Final</li>
</ul>
",https://stackoverflow.com/questions/75380525/quarkustest-class-cast-exception-buildchainbuilder,"['java', 'gradle', 'junit', 'quarkus']",115,False,0,1
Testing against a Docker image server on CircleCI?,"<p>I'm trying to write a test suite for my application.  My application is a downloader; it takes arbitrary web request information (URLs, headers, cookies, etc) and sends a request and returns the response.</p>
<p>In order to test the downloading functionality of this application, I'm trying to stand up an instance of <a href=""http://httpbin.org/"" rel=""nofollow noreferrer"">HttpBin</a> inside my test environment using their provided Docker image, run queries against it, and then spin it down once the test is done.  Clearly I can't run this except through Docker, as it is a Docker image that is provided.</p>
<p>This all works fine on my local machine; I can spin up the image, set up port-forwarding, and send my queries and receive responses.  The problem is, I can't seem to make this work when I run m test in my CI/CD pipeline (powered by CircleCI).  For some reason, I can't get my test server to talk to my HttpBin instance no matter what I try.  I've tried checking the locations of the 2 images and I got something that looks like this when I run <code>docker container list</code> on CircleCI:</p>
<pre><code>CONTAINER ID   IMAGE                                            COMMAND                  CREATED          STATUS                  PORTS                               NAMES
74b99c53fd97   kennethreitz/httpbin                             &quot;gunicorn -b 0.0.0.0…&quot;   1 second ago     Up Less than a second   0.0.0.0:80-&gt;80/tcp, :::80-&gt;80/tcp   httpbin
5d27d41efd94   cimg/node:lts-browsers                           &quot;/docker-entrypoint.…&quot;   30 seconds ago   Up 27 seconds                                               jolly_golick
</code></pre>
<p>So it appears that the HttpBin instance and my test instance (running inside an <code>lts-browsers</code> instance) are both child VMs running inside an integration server, and it looks like port-forwarding is set up from the integration server to HttpBin, meaning I should be able to make <code>host.docker.internal</code> calls, but those don't work (<code>ERR_NAME_NOT_RESOLVED</code>).</p>
<p>Does anyone have any suggestions on how to make this work?  It seems like a common enough use case for E2E/Integration testing that it really should work and it's odd that it doesn't.</p>
<p>Also, here's my test config from <code>package.json</code>:</p>
<pre><code>{
    &quot;pretest&quot;: &quot;docker stop httpbin || true &amp;&amp; docker container rm httpbin || true &amp;&amp; docker run -d -p 80:80 --name=httpbin kennethreitz/httpbin&quot;,
    &quot;test&quot;: &quot;jest&quot;,
    &quot;posttest&quot;: &quot;docker stop httpbin &amp;&amp; docker container rm httpbin&quot;
}
</code></pre>
",https://stackoverflow.com/questions/76282073/testing-against-a-docker-image-server-on-circleci,"['node.js', 'docker', 'networking', 'integration-testing', 'circleci']",24,False,0,0
How to map a column of a composite foreign key to a column of a composite primary key in JPA,"<p>Given there are two tables <code>client</code> and <code>device</code> with a one(<em>client</em>)-to-many(<em>devices</em>) relation. The simplified schemas of the table are:</p>
<pre class=""lang-sql prettyprint-override""><code>TABLE client (
  id,
  import_date,
  PRIMARY_KEY (id, import_date)
)
</code></pre>
<p>and</p>
<pre class=""lang-sql prettyprint-override""><code>TABLE device (
  id,
  import_date,
  client_id,
  PRIMARY_KEY (id, import_date),
  FOREIGN_KEY (client_id -&gt; client.id, import_date -&gt; client.import_date)
)
</code></pre>
<hr />
<p>Note: The column <code>device.import_date</code> is part of the primary key as well as part of the foreign key.</p>
<hr />
<p>Unfortunately I fail to describe the above structure in JPA.<br />
This is my humble attempt (getters, setters, implemented interfaces, etc. omitted):</p>
<pre class=""lang-java prettyprint-override""><code>public class ImportId {
    private Integer id;
    private LocalDate importDate;
}

@Entity
@IdClass(ImportId.class)
public class Client {
    @Id
    private Integer id;
    @Id
    private LocalDate importDate;
}


@Entity
@IdClass(ImportId.class)
public class Device {
    @Id
    private Integer id;
    @Id
    private LocalDate importDate;
    @ManyToOne
    //@MapsId(&quot;importDate&quot;) &lt;-- does not work
    //@JoinColumn
    //@JoinColumn           &lt;-- also not working
    private Client client;
}
</code></pre>
<p>Using <code>@MapsId</code> together with <code>@IdClass</code> does nothing special resulting in an extra column <code>client_import_date</code> in the <code>device</code> table, which is undesirable.</p>
<p>I've also tried using <code>@MapsId</code> in conjunction with <code>@Embeddable</code> without success. It fails with</p>
<pre><code>org.hibernate.PropertyNotFoundException: Could not locate field name [id] on class [java.time.LocalDate]
</code></pre>
<p>Can someone help me with this issue?<br />
Thanks a lot!</p>
<hr />
<h4>Update 1 (responding to Phil Ku's approach)</h4>
<p>At first glance, this looks promising. Hibernate does not create the &quot;client_import_date&quot; column and sets the foreign key correctly.
However, I can not save a device entity. Executing this code</p>
<pre class=""lang-java prettyprint-override""><code>// var client = clientRepository.save(new Client(1234, LocalDate.now());
deviceRepository.save(new Device(567, LocalDate.now(), client));
</code></pre>
<p>Hibernate generates the following SQL:</p>
<pre class=""lang-sql prettyprint-override""><code>INSERT INTO device(client_id, import_date, id) VALUES(?,?,?);
</code></pre>
<p>then tries to bind the following parameters:</p>
<pre><code>[1] as [INTEGER] - [1234]
[2] as [DATE] - [2023-03-22]
[3] as [INTEGER] - [567]
[4] as [DATE] - [2023-03-22]
</code></pre>
<p>and then throws the exception <code>Invalid value &quot;4&quot; for parameter &quot;parameterIndex&quot;</code>. Of course it fails, because there is no fourth parameter to bind to. Any thoughts why Hibernate's parameter list does not match the insert statement?</p>
<h5>Update 1.1</h5>
<p>The Hibernate exception described in <strong>Update 1</strong> appears to occur only in conjunction with the H2 platform. So integration testing might be broken in this scenario. Tested versions: Hibernate 6.1.7 and H2 2.1.214, both shipped with Spring Boot 3.0.4.<br />
Using MariaDB driver everything of Phil Ku's approach works fine. Tracing the Hibernate output reveals that there are still four parameter candidates, selecting the first three doesn't seem to be a problem though.</p>
<hr />
<h4>Update 2</h4>
<p>The next transaction related issue arises.<br />
When I execute the following code</p>
<pre class=""lang-java prettyprint-override""><code>var importDate = LocalDate.now();
var client = clientRepository.save(new Client(100, importDate));
var device1 = new Device(1, importDate, client);
var device1 = new Device(2, importDate, client);
deviceRepository.saveAll(List.of(device1, device2));
</code></pre>
<p>the exception</p>
<pre><code>SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`device`, CONSTRAINT `...` FOREIGN KEY (`client_id`, `import_date`) REFERENCES `client` (`id`, `import_date`))
</code></pre>
<p>is thrown.</p>
<p>When I instead call <code>deviceRepository.save</code> for each device, everything works just fine.<br />
I'm not able to mimic this behavior outside of JPA/Hibernate context. Executing the appropriate INSERT statements directly on the database – either in one or in two transactions – never results in a constraint violation.</p>
<p>Any fresh ideas on that?</p>
<hr />
<h4>Update 3</h4>
<p>Based on K.Nicholas' and Phil Ku's comments I have re-designed my database schemas. Now, the <code>client</code> table has an ordinary numeric single column primary key and the <code>import_date</code> column is just part of a unique constraint key with the <code>(client-)id</code> column. The primary key is then referenced by the <code>device</code> table.<br />
Feels a bit like a workaround, but it works perfectly fine though.<br />
Thanks everybody for helping.</p>
",https://stackoverflow.com/questions/75807251/how-to-map-a-column-of-a-composite-foreign-key-to-a-column-of-a-composite-primar,"['java', 'hibernate', 'jpa']",132,False,1,3
Testing a blocking process in Rust,"<p>I am trying to build this utility that watches for file changes and execute some commands the original program is infinite loop that waits for some events to happen to the files currently being watched. I am trying to do some integration testing but with no luck I tried a lot of stuff would really appreciate the help.</p>
<p>This is what I am currently trying to do:</p>
<h1>The Test</h1>
<pre><code>#[test]
fn one_file_works() { 
    let file_to_watch = &quot;tests/test_file/hello.txt&quot;;
    let mut auto = Command::cargo_bin(&quot;my_utility&quot;).unwrap();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(2000));
        println!(&quot;Modifying file&quot;);
        std::fs::write(file_to_watch, &quot;&quot;).unwrap();
    });

    println!(&quot;Starting command&quot;);
    let cmd = auto
        .write_stdin(file_to_watch)
        .args(&amp;[&quot;-t&quot;, &quot;5&quot;, &quot;echo -n Hello World&quot;]);
    println!(&quot;Finishing command&quot;);
    
    println!(&quot;Asserting&quot;);
    cmd.assert().success().stdout(&quot;Hello World&quot;);
}
</code></pre>
<h1>Quick overview of how my_utility works:</h1>
<p>the utility takes some file/files from stdin and watches them for changes the modify timestamp like. meaning every time I save or write to a file it's timestamp changes and that triggers an event and that event causes it do execute the command in the arguments.</p>
<p>typical example of a usage case:</p>
<p><code>echo &quot;hello.txt&quot; | my_utility &quot;echo -n Hello World&quot; </code>
So I pipe the name of the file hello.txt and that fire up my_utility in a loop {} waiting for that file to change to execute the command in quotes.and for the -t 2 it just means timeout after 2 seconds instead of looping forever.</p>
<h1>What does the test does?</h1>
<p>Essentially I am trying to run my program in the main thread and I am running it with -t 5 which means it should wait 5 seconds for changes for events for the files currently being watched. and in a different thread I am trying to write to a file that's being watched and at the end I am asserting stdout with the expected output.</p>
<h1>Output</h1>
<p>I added some debug statements to get a feel for what the test is doing but I can't quite wrap my head why it's outputting what it's outputting.</p>
<p>Here is the test output:
Starting command
Finishing command
Asserting
Modifying file</p>
<p>Which for me makes absolutely no sense because I am running a different thread which should take around 1 second(because of the delay I added to wait for my utility to up and running waiting for events) and the main thread is blocked because the utility should be blocking the main thread for 5 seconds at least so I was expecting something like:
Starting command
Modifying file
Finishing command
Asserting</p>
<h1>Other possible solutions?</h1>
<p>I really haven't had the need to test something like this before but would love to know if there is a better way to test such a utility and just dump my code I provided and start with a better cleaner way.</p>
",https://stackoverflow.com/questions/76131564/testing-a-blocking-process-in-rust,"['multithreading', 'asynchronous', 'testing', 'rust']",35,False,0,0
What&#39;s the best settings/configuration option for a REST server object extension based in .NET Core 6.0?,"<p>I have a legacy ESRI ArcGIS Server Object (SOE) extension written against ESRI's old 32-bit ArcObjects framework (.NET Framework 4.7.1).  My group is looking to upgrade this to ESRI's new ArcGIS Enterprise 11.1 framework/SDK (.NET Core 6.0).  The new SDK was intentionally designed by ESRI to map very easily 1:1 to the old ArcObjects version, so from a raw coding standpoint it looks pretty straightforward.  The SOE is designed to be paired to an existing ESRI REST map service and exposes a number of endpoints that can be queried directly.</p>
<p>In the legacy tools, I made liberal use of the .NET Framework Settings.Configuration &quot;Settings&quot; files to codify a lot of the string-handling that's necessary within the tool.  In an ideal world I understand it would be better to inject the whole mess via dependency-injection. However, it's all pretty static stuff. Also, it is inherited code and we have limited resources, so I had to be judicious about how and against what content to apply our integration testing.  It was all I could do to wrangle all the hard-coded strings in the original code into these settings files to begin with.</p>
<p>I'm interested in suggestions for what the best approach would be to building in support for configuration to the new .NET Core-based solution. Unfortunately, in an SOE I don't have easy access to the Microsoft.AspNetCore library or the WebApplication object so I've been unsuccessful in creating and accessing configuration objects so far. I'm open to setting the configuration up in a separate project and injecting it in in the interest of supporting better testing practice.  However, in that context the problem remains for where to start, whether a .NET Core IConfiguration approach could be adapted somehow (help!), or whether some other tactic would be better.  I'd like a solution which I can most easily adapt and maintain the abstraction advantages of the old strongly-typed .NET Framework settings files.  And if it turns out the existing .NET Core Configuration API / Options approach is recommended, I'd be very grateful for some indication of how I might best adapt those to my project (since it's unclear to me at the moment).</p>
<hr />
<p>I've done some research into the <a href=""https://www.c-sharpcorner.com/article/configuration-in-asp-net-core/#:%7E:text=Configuration%20In%20ASP.NET%20Core.,grouped%20into%20multi%2Dlevel%20hierarchy."" rel=""nofollow noreferrer"">.NET Core Configuration</a> and <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.0"" rel=""nofollow noreferrer"">Options</a> patterns for .NET Core web applications.  However, these seem to take advantage of the availability of the IConfiguration / Microsoft.AspNetCore.Builder middleware and carry assumptions about how the configuration would be initialized as part of web application startup procedure (which doesn't exist for an SOE).  References to those libraries also aren't immediately available in the boilerplate project when initiating an ArcGIS Enterprise 11.1 ESRI SOE project within Visual Studio.  So the examples provided don't give me a full understanding of whether that approach is appropriate for my project.</p>
",https://stackoverflow.com/questions/76344432/whats-the-best-settings-configuration-option-for-a-rest-server-object-extension,"['rest', '.net-core', 'configuration', 'arcgis', 'arcgis-server']",23,False,0,0
