<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tinytella（トリン） on Medium]]></title>
        <description><![CDATA[Stories by Tinytella（トリン） on Medium]]></description>
        <link>https://medium.com/@trinh130895?source=rss-3a50902143b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oHi3twmDtf_DFvFnPlKCPg.png</url>
            <title>Stories by Tinytella（トリン） on Medium</title>
            <link>https://medium.com/@trinh130895?source=rss-3a50902143b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:19:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@trinh130895/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Array-Based Search in the Spring Framework]]></title>
            <link>https://medium.com/goalist-blog/array-based-search-in-the-spring-framework-424bb9ea8fc0?source=rss-3a50902143b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/424bb9ea8fc0</guid>
            <dc:creator><![CDATA[Tinytella（トリン）]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 16:40:04 GMT</pubDate>
            <atom:updated>2023-10-11T07:30:06.106Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Well, I guess it’s safe to say that you’ve encountered this requirement for a search API at least once — finding objects by an array of keywords.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-_6NtWSJhALquxnUkHM1g.png" /></figure><p>Even so, I still can’t seem to remember it and make the development process less painful each time. Therefore, I would like to share some common cases through this article.</p><p>Technologies I am using:</p><ul><li>Java 17</li><li>Spring Boot 3.0.6</li></ul><h3><strong>1. JPQL Queries</strong></h3><p>If the condition is not too complex, we can simply write it in JPQL like this:</p><pre>@Query(value = &quot;&quot;&quot;<br>        from manuscripts m join post_labels lb<br>        on m.id = lb.manuscript.id where lb.label.id in :featureIds<br>    &quot;&quot;&quot;)<br>    List&lt;Manuscript&gt; findByFeatureLabelsIn(List&lt;Long&gt; featureIds);</pre><p>Notes: Make sure that the <strong>List </strong>parameter do not have <strong>NULL </strong>case, otherwise you might get wrong result.</p><p>If you don’t have the option to avoid passing NULL values through the List parameters, you might consider using COALESCE.</p><blockquote>FYI, the <strong>COALESCE</strong>() function returns the first non-null value in a list.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*DA7Q47JSlkP6v6cjigE9zQ.png" /><figcaption>JQPL</figcaption></figure><p>However, it doesn’t appear that COALESCE works well with JPQL. 🤷</p><p>Here is an error message you might have seen in this case.</p><pre>06-10-2023 20:44:19.963 ERROR [http-nio-8080-exec-3] --- o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions [138] : Operand should contain 1 column(s)<br>org.springframework.dao.DataIntegrityViolationException: JDBC exception executing SQL [select r1_0.id,r1_0.title from manuscripts r1_0 join post_labels m1_0 on r1_0.id=m1_0.manuscript_id where (r1_0.is_deleted=0) and (coalesce((?,?)) is null or m1_0.label_id in(?,?))];</pre><h3><strong>2. Native Queries</strong></h3><p>Don’t give up; fortunately, you can write it in a <strong>Native Query</strong>. 💁</p><blockquote>For those who haven’t known yet, we can add ‘nativeQuery = true’ to switch JPQL into Native Query mode.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*13XBBIevjVTOYZXE6ToBnA.png" /><figcaption>Native Query</figcaption></figure><p>Well, it looks good with <strong>Native Query</strong>, right? At least, we don’t see the red line in syntax by IntelliJ compiler. However, it’s different from what we expected; it still gives us an error.</p><pre>06-10-2023 21:04:27.182 WARN  [http-nio-8080-exec-4] --- o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions [133] : SQL Error: 1064, SQLState: 42000<br>06-10-2023 21:04:27.182 ERROR [http-nio-8080-exec-4] --- o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions [138] : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near &#39;null&#39; at line 4<br>org.springframework.dao.InvalidDataAccessResourceUsageException: JDBC exception executing SQL [    select m.*<br>    from manuscripts m join post_labels lb<br>    on m.id = lb.manuscript_id where<br>    coalesce(?) is null or lb.label_id in ?<br>]; SQL [n/a]</pre><p>It is showing that the statement still doesn’t accept NULL after the IN operator. Let’s pass the SQL statement that we obtained from the console into the SQL Editor to figure it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*g5L6E-BDyiTOm7UrK9TwTw.png" /><figcaption>MySQL Workbench</figcaption></figure><blockquote>Okay, so here is the memorable thing to save you time when working with COALESCE and the IN operator: please make sure you wrap your parameter inside parentheses like this <strong>(:featureIds)</strong>.</blockquote><pre>    @Query(value = &quot;&quot;&quot;<br>        select m.*<br>        from manuscripts m join post_labels lb<br>        on m.id = lb.manuscript_id where<br>        coalesce(:featureIds) is null or lb.label_id in (:featureIds)<br>    &quot;&quot;&quot;, nativeQuery = true)<br>    List&lt;Manuscript&gt; findByFeatureLabelsIn(List&lt;Long&gt; featureIds);</pre><p>The fun fact is, I used to use COALESCE in Java 11, and when I switched to Java 17, I thought maybe it no longer works with the current version (17). So, it took me a while to struggle in finding other ways before I came back to realize what the problem was with this powerful function (in my opinion).</p><p>Up to now, you might think that Native Query is enough. Have you ever had to write a search SQL with more than 10 fields that need to be compared? Well, it’s not a good idea to write it all in one query, I guess.</p><h3><strong>3. Advanced Spring Data JPA — Specifications</strong></h3><p>Besides the two methods mentioned above, you may already be familiar with the Criteria API.</p><p>As the author is saying, to be able to define reusable <strong>Predicates</strong>, they have introduced the <a href="https://docs.spring.io/spring-data/jpa/reference/jpa/specifications.html"><strong>Specification</strong></a><strong> </strong>interface. Although it’s not stable yet, it’s still worth giving it a try. 😉</p><p>Of course, there are many interesting aspects that you can explore, but in this post, I will just focus on how to deal with List parameters.</p><p>Before using it, I will have to add it to the <strong>Repository </strong>layer. Here, I’ll give you an example of how complex SQL I have to write, and then I’ll transform it into <strong>Specifications</strong>.</p><pre>@Repository<br>public interface ManuscriptRepository extends JpaRepository&lt;Manuscript, Long&gt;, JpaSpecificationExecutor&lt;Manuscript&gt; {<br><br>@Query(value = &quot;&quot;&quot;<br>            select m.* from manuscripts m<br>            join occupations occ on m.occupation_id = occ.id<br>            join company_locations loc on m.location_id = loc.id<br>            join post_labels lb on m.id = lb.manuscript_id<br>            join companies c on c.id = loc.company_id<br>            where m.start_date &lt;= current_time() and m.public_status = &#39;PUBLIC&#39;<br>            and (:keywords is NULL or m.title REGEXP (:keywords))<br>            and (:keywords is NULL or m.job_description REGEXP (:keywords))<br>            and (:keywords is NULL or loc.address REGEXP (:keywords))<br>            and (:keywords is NULL or c.companyName REGEXP (:keywords))<br>            and (:keywords is NULL or c.introduction REGEXP (:keywords))<br>            and (:keywords is NULL or c.summary REGEXP (:keywords))<br>            and (:companyId is NULL or c.id = :companyId)<br>            and (COALESCE(:occupations) is NULL or m.small_occupation_id in (:occupations))<br>            and (COALESCE(:prefectures) is NULL or loc.location in (:prefectures))<br>            and lb.manuscript_id in (<br>                select distinct label2.manuscript_id from post_labels label2<br>                where (COALESCE(:featureIds) is NULL OR label2.label_id in (:featureIds))<br>                group by label2.manuscript_id<br>                having count(label2.label_id) &gt;= :featureCount)<br>            &quot;&quot;&quot;, nativeQuery = true)<br>    List&lt;Manuscript&gt; countManuscriptBySearchCondition(<br>            String keywords,<br>            Set&lt;Long&gt; smallOccupationIds,<br>            Set&lt;String&gt; prefectures,<br>            Set&lt;Long&gt; featureIds,<br>            Long companyId,<br>            int featureCount<br>    );<br>}</pre><ol><li><strong>Specification Definition</strong></li></ol><pre>public class ManuscriptSpecification {<br>    private ManuscriptSpecification() {<br>    }<br><br>    //TODO: write many predicates depending on how many conditions we have<br>    public static Specification&lt;Manuscript&gt; keywords(List&lt;String&gt; keywords) {<br>        // return your predicates<br>    }<br><br>    public static Specification&lt;Manuscript&gt; publicStatus(ManuscriptStatus status) {<br>        // return your predicates<br>    }<br><br>...<br><br>    public static Specification&lt;Manuscript&gt; occupationIds(Set&lt;Long&gt; smallOccupationIds) {<br>        // return your predicates<br>    }</pre><p>2. <strong>Sub Queries</strong></p><p>There is a part where I have to select data from another result table, so we have to create a subquery.</p><pre> public static Specification&lt;Manuscript&gt; featureIdIn(Set&lt;Long&gt; featureIds) {<br>        return featureIds == null ? null : (root, query, cb) -&gt; {<br>            Subquery&lt;Long&gt; subQuery = query.subquery(Long.class);<br>            Root&lt;PostLabel&gt; subRoot = subQuery.from(PostLabel.class);<br><br>            subQuery.select(subRoot.get(&quot;manuscript&quot;).get(&quot;id&quot;));<br>            subQuery.groupBy(subRoot.get(&quot;manuscript&quot;).get(&quot;id&quot;));<br>            subQuery.having(cb.greaterThanOrEqualTo(cb.count(subRoot), cb.literal((long) featureIds.size())));<br>            Predicate labelIdPredicate = subRoot.get(&quot;label&quot;).get(&quot;id&quot;).in(featureIds);<br>            subQuery.where(labelIdPredicate);<br><br>            return cb.in(root.get(&quot;id&quot;)).value(subQuery);<br>        };<br>    }</pre><blockquote>The PostLabels table represents a many-to-many relationship between the Manuscripts and Labels tables.</blockquote><pre>public class PostLabel{<br><br>    @EmbeddedId<br>    private PostLabelEmbeddedID id;<br><br>    @ManyToOne<br>    @MapsId(&quot;manuscriptId&quot;)<br>    Manuscript manuscript;<br><br>    @ManyToOne<br>    @MapsId(&quot;labelId&quot;)<br>    PostLabel label;<br>}</pre><pre>public class PostLabelEmbeddedID implements Serializable {<br><br>    @ManyToOne<br>    Manuscript manuscript;<br><br>    @ManyToOne<br>    PostLabel label;<br>}</pre><p>3. <strong>Search <em>LIKE </em>with many keywords</strong></p><p>I had a headache trying to find a solution for searching articles that contain one of these keywords in its title, job description, location address, or company description, etc. I had been looking for an answer on how to combine the <strong>IN </strong>operator with a wildcard character ‘<strong><em>%s%</em></strong>’ but there was no hope for that.</p><p>And I found this “<strong>REGEXP</strong>” operator instead.</p><blockquote><strong>REGEXP </strong>in <strong>MySQL </strong>serves as a potent tool for pattern matching in text, capable of matching nearly any pattern within a string.</blockquote><p>Here is the format for its usage:</p><pre>SELECT * FROM manuscripts where title REGEXP &#39;１２３|新業務|エンジニア｜TX, USA&#39;;</pre><ul><li>And here is how I implemented it in the <strong>Specification </strong>class:</li></ul><pre>public static Specification&lt;Manuscript&gt; keywords(List&lt;String&gt; keywords) {<br>    return keywords == null ? null : (root, query, cb) -&gt; {<br>        Expression&lt;String&gt; searchText = cb.literal(wrapKeywords(keywords));<br>        Predicate[] predicates = {<br>                cb.isTrue(cb.function(&quot;regexp_like&quot;, Boolean.class, root.get(&quot;title&quot;), searchText)),<br>                cb.isTrue(cb.function(&quot;regexp_like&quot;, Boolean.class, root.get(&quot;jobDescription&quot;), searchText)),<br>                cb.isTrue(cb.function(&quot;regexp_like&quot;, Boolean.class, root.get(&quot;location&quot;).get(&quot;company&quot;).get(&quot;summary&quot;), searchText)),<br>                cb.isTrue(cb.function(&quot;regexp_like&quot;, Boolean.class, root.get(&quot;location&quot;).get(&quot;company&quot;).get(&quot;companyName&quot;), searchText)),<br>                cb.isTrue(cb.function(&quot;regexp_like&quot;, Boolean.class, root.get(&quot;location&quot;).get(&quot;company&quot;).get(&quot;introduction&quot;), searchText)),<br>                cb.isTrue(cb.function(&quot;regexp_like&quot;, Boolean.class, root.get(&quot;location&quot;).get(&quot;address&quot;), searchText))<br>        };<br>        return cb.or(predicates);<br>    };<br>}</pre><pre>public static String wrapKeywords(List&lt;String&gt; values) {<br>    return values == null ? &quot;&quot; : String.join(&quot;|&quot;, values);<br>}</pre><h3>Summary</h3><p>Thank you for taking the time to read! Below, I have gathered several important points for you.</p><ol><li><strong>COALESCE</strong>() is your friend: When dealing with potential NULL values in your array parameters, consider using <strong>COALESCE</strong>(). It can save you from unexpected hiccups in your queries.</li><li><strong>Native Query</strong>: If you find yourself facing complex SQL scenarios, don’t hesitate to switch to Native Query mode. It might just be the solution you need to tackle those intricate searches.</li><li><strong>Criteria API</strong> and <strong>Specifications</strong>: If the SQL has something that can be reused, consider using these tools to make your code cleaner and more maintainable.</li><li>Pattern Matching with <strong>REGEXP</strong>: If you’re dealing with pattern matching in text, and the <strong>LIKE </strong>operator isn’t providing the assistance you need, remember that <strong>REGEXP </strong>in MySQL can be your <em>go-to</em> tool.</li></ol><p>Hopefully, these tips should help you save your time with the search function. Happy coding, and may your searches always yield the results you seek!</p><p>See you! 🙋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=424bb9ea8fc0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/array-based-search-in-the-spring-framework-424bb9ea8fc0">Array-Based Search in the Spring Framework</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Painful experience with Next13 deployment in GCP]]></title>
            <link>https://medium.com/goalist-blog/painful-experience-with-next13-deployment-in-gcp-b35864bac303?source=rss-3a50902143b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35864bac303</guid>
            <dc:creator><![CDATA[Tinytella（トリン）]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 16:23:44 GMT</pubDate>
            <atom:updated>2023-09-08T00:41:57.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mllgho23BhL_MH3Rski_yA.png" /></figure><p><em>I wrote this story shortly after we were able to move forward on deploying a React application in Google Cloud Platform (GCP). Since I am just a web developer, infrastructure is truly something horrible to me. However, in some unexpected cases, we also have to involving in checking where the problem of failed deployment comes from. Therefore, I would like to save it as my memorable notes for the later use.</em></p><p>First of all, let’s see what do we have:</p><ul><li>2 applications which are built in Next 13 (for Media and Management side)</li><li>Google Cloud Platform (GCP)</li><li>Terraform</li><li>Github Action</li></ul><h3><strong>I. Deployment Setup</strong></h3><ol><li><strong>Github Actions configuration</strong></li></ol><ul><li><a href="https://hyperskill.org/learn/step/20403">As far as I have researched</a>, we can simply understand that there are two main components of Github Actions: <strong>Event </strong>and <strong>Workflow</strong>.</li></ul><blockquote><strong>***Brief explanations:</strong></blockquote><ul><li>name: the name of the workflow as it will appear in the “Actions” tab</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*bnUOICXpZY2cV491FBkBiw.png" /><figcaption>The name displays in Actions Tab</figcaption></figure><ul><li>on: used to define which <a href="https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows">events</a> can cause the workflow to run. In our project, we use <strong><em>label </em></strong>event.</li></ul><p>When you create a pull request, you will see it on the right side of the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSXcNNBQ33ycfBTapFmykg.png" /></figure><ul><li>jobs: used to group a list of jobs which are run in one workflow.</li></ul><p>***There are two ways to name a job:</p><p>If you don’t specify the name explicitly, it will use the name below “jobs” as a default</p><pre>jobs:<br>  terraform-apply:<br>    runs-on: ubuntu-latest<br>    timeout-minutes: 15</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*f0y5nEITTkHFtHjwlm27Ww.png" /></figure><p>On the other hand, it will use the name in the configuration.</p><pre>jobs:<br>  deploy:<br>    name: deploy dev<br>    runs-on: ubuntu-latest<br>    timeout-minutes: 15</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*MhzaEnAFu8gLG6kiZlul1A.png" /></figure><ul><li>steps: used to group all the actions taken in one job.</li></ul><p>There are two main keywords: <strong>uses </strong>and <strong>run</strong>.</p><p>To set it up, we will need a YAML file like below:</p><pre>name: dev<br><br>on:<br>  pull_request:<br>    types:<br>      - labeled<br>    paths-ignore:<br>      - &quot;**.md&quot;<br>      - &quot;.gitignore&quot;<br>    branches:<br>      - main<br><br>jobs:<br>  deploy-dev:<br>    runs-on: ubuntu-latest<br>    environment:<br>      name: dev<br>    timeout-minutes: 20<br>    if: |<br>      ( github.event.action == &#39;labeled&#39; &amp;&amp; github.event.label.name == &#39;dev&#39; ) |<br>    steps:<br>      - name: &lt;the name will be displayed in Action log)<br>        uses: &lt;check out a repository or an image which is uploaded in the bucket and run it&gt;<br>      - name: &lt;the name will be displayed in Action log)<br>        run: &lt;run a command line&gt;</pre><p>FYI, please refer this post:</p><p><a href="https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions">https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions</a></p><p><strong>2. Docker configuration</strong></p><p><em>According to statistics collected on the Internet, there are more than 7 million people using Docker every day. It’s no wonder that setting up Docker is one of the steps to prepare for deployment.</em></p><p>(I’m sorry that I will have to cover <a href="https://docs.docker.com/build/guide/intro/">Docker in detail</a> in another post because it’s not really what I would like to share now, but I show you where it will be used in our project. It was defined as a step in the workflow mentioned above)</p><pre>- name: docker build and push<br>  uses: docker/build-push-action@v3<br>  with:<br>    push: true<br>    file: docker/node/Dockerfile<br>    context: .<br>    build-args: env=dev<br>    tags: asia-northeast1-docker.pkg.dev/&lt;path in gcp&gt;:${{ github.sha }}</pre><p><strong>3. Terraform configuration</strong></p><p>As I have admitted from the beginning, I honestly have no idea about anything related to infrastructure. So, let me just say what I understand is that we will need a source to setup the terraform environment and it will be used as a final step after building the image above.</p><pre>- name: setup terraform<br>  uses: hashicorp/setup-terraform@v2<br>  with:<br>    terraform_version: 1.4.4<br><br>- name: terraform/management apply<br>  run: bash terraform/management/bin/apply.sh dev<br>  env:<br>    TF_VAR_fe_management_image_tag: ${{ github.sha }}</pre><h3>II. Deployment Errors</h3><p>The situation we faced was that only one source was deployed successfully but the configuration of both was the same. However, both initial sources were able to deployed once.</p><p>And since we weren’t able to deploy two current sources successfully at the same time, there were a lot of assumptions appeared in our mind.</p><ol><li><strong>Failed in </strong><a href="https://cloud.google.com/run/docs/configuring/healthchecks#http-startup-probe"><strong>checking</strong></a><strong> the healthy status of an instance</strong></li></ol><pre>STARTUP HTTP probe failed 3 times consecutively for container &quot;bext-fe-management-1&quot; on path &quot;/healthcheck&quot;. The instance was not started.</pre><p>When the first time we met this error, we tried increasing <strong>periodSeconds</strong> in the configuration and then, it passed. However, the instance still failed.</p><p><strong>2. Tried running Docker images locally</strong></p><p>Then, we came up with an idea of downloading built Docker image from GCP and tried running it locally. Of course, it could run normally.</p><p>Here you can upload and download your Docker images:</p><p><a href="https://cloud.google.com/build/docs/building/store-artifacts-in-artifact-registry">Store artifacts in Artifact Registry | Cloud Build Documentation | Google Cloud</a></p><p>Luckily, there were a small difference outputted in the log:</p><ul><li>The initial source:</li></ul><pre>Listening on port 3000 url: http://localhost:3000</pre><ul><li>The current source which was always failed:</li></ul><pre>- ready started server on 127.0.0.1:3000, url: http://127.0.0.1:3000</pre><p>Besides the strange log output, another thing was that we had no way to access the /healthcheck api as well.</p><ul><li>The initial source:</li></ul><pre>/app # wget http://127.0.0.1:3000/healthcheck<br>Connecting to 127.0.0.1:3000 (127.0.0.1:3000)<br>saving to &#39;healthcheck&#39;<br>healthcheck          100% |********************************************************************************************************************************************************************************************************************************| 16881  0:00:00 ETA<br>&#39;healthcheck&#39; saved</pre><ul><li>The current source which was always failed:</li></ul><pre>/app # wget http://127.0.0.1:3000/healthcheck<br>Connecting to 127.0.0.1:3000 (127.0.0.1:3000)<br>wget: can&#39;t connect to remote host (127.0.0.1): Connection refused</pre><p><strong>3. Figured out how to debug the instance.</strong></p><p>As those who have experience working with React applications will know this log must be output from <strong>server.js</strong></p><p>In <strong>Next13</strong>, we just need to specify <a href="https://nextjs.org/docs/pages/api-reference/next-config-js/output"><strong>standalone </strong></a>mode so it will help us to generate this file, which implicitly causes this problem.</p><ul><li>To check <strong>server.js</strong> from a running container, you can use this command:</li></ul><pre>docker exec -it &lt;containerId&gt; /bin/bash</pre><p>Or clicking on this <strong>CLI </strong>icon if you’re using Docker GUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KDG7MXW53pm7onpa4_DTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*zHLGEvC22G5Aw7sXBryHyw.png" /><figcaption>List of React application’s files inside a container</figcaption></figure><h3><strong>Can you guess what we saw in the server.js?</strong></h3><ul><li>The initial source:</li></ul><pre>const { createServerHandler } = require(&#39;next/dist/server/lib/render-server-standalone&#39;)<br><br>...omit the similarity above...<br><br>process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(nextConfig)<br><br>const server = http.createServer(async (req, res) =&gt; {<br>  try {<br>    await handler(req, res)<br>  } catch (err) {<br>    console.error(err);<br>    res.statusCode = 500<br>    res.end(&#39;Internal Server Error&#39;)<br>  }<br>})<br><br>if (<br>  !Number.isNaN(keepAliveTimeout) &amp;&amp;<br>    Number.isFinite(keepAliveTimeout) &amp;&amp;<br>    keepAliveTimeout &gt;= 0<br>) {<br>  server.keepAliveTimeout = keepAliveTimeout<br>}<br>server.listen(currentPort, async (err) =&gt; {<br>  if (err) {<br>    console.error(&quot;Failed to start server&quot;, err)<br>    process.exit(1)<br>  }<br><br>  handler = await createServerHandler({<br>    port: currentPort,<br>    hostname,<br>    dir,<br>    conf: nextConfig,<br>  })<br><br>  console.log(<br>    &#39;Listening on port&#39;,<br>    currentPort,<br>    &#39;url: http://&#39; + hostname + &#39;:&#39; + currentPort<br>  )<br>});</pre><ul><li>The current source which was always failed:</li></ul><pre>const { startServer } = require(&#39;next/dist/server/lib/start-server&#39;)<br><br>...omit the similarity above...<br><br>process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(nextConfig)<br><br>if (<br>  Number.isNaN(keepAliveTimeout) ||<br>  !Number.isFinite(keepAliveTimeout) ||<br>  keepAliveTimeout &lt; 0<br>) {<br>  keepAliveTimeout = undefined<br>}<br><br>startServer({<br>  dir,<br>  isDev: false,<br>  config: nextConfig,<br>  hostname,<br>  port: currentPort,<br>  allowRetry: false,<br>  keepAliveTimeout,<br>  useWorkers: !!nextConfig.experimental?.appDir,<br>}).catch((err) =&gt; {<br>  console.error(err);<br>  process.exit(1);<br>});</pre><p><strong>4. Be careful with the version using in package.json</strong></p><p>After about two weeks of struggling with this confusing problem, this comment literally saved our lives.</p><p><a href="https://github.com/vercel/next.js/issues/53171#issuecomment-1689050295">https://github.com/vercel/next.js/issues/53171#issuecomment-1689050295</a></p><p>Finally, we could find the root of this problem, it’s from this line in <strong>package.json</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*o6GOYA3u1li8IYX4h7gK2g.png" /></figure><p>After degrading it into 13.4.1 and <strong>remove ^</strong> also, we was happy to announce that two applications were able to be deployed at the same time.</p><p>And why do I have to emphasize “remove ^”, I hope you find <a href="https://saturncloud.io/blog/whats-the-difference-between-tilde-and-caret-in-packagejson/"><strong>this article</strong></a><strong> </strong>useful.</p><h3>III. Summary</h3><p>There are a few lessons I learned through this problem:</p><ol><li>Try to build up the infrastructure as soon as you start implementing the project. And be sure that every source code can be deployed successfully once.</li><li>Try to verify the deployed built image. Although it’s built and run successfully in the local, it doesn’t mean it will work the same in another environment.</li><li>Pay most attention to the version of the dependencies. If we don’t want to encounter this problem in someday, it would be better to update the version manually after we can make sure that the new version will not be degraded.</li></ol><p>Okay, last but not least, thank you for spending time to read my painful story.</p><p>Hope you have a nice day / night ~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35864bac303" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/painful-experience-with-next13-deployment-in-gcp-b35864bac303">Painful experience with Next13 deployment in GCP</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration Test with Spring Boot]]></title>
            <link>https://medium.com/goalist-blog/integration-test-with-spring-boot-5222c38ad3f3?source=rss-3a50902143b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5222c38ad3f3</guid>
            <dc:creator><![CDATA[Tinytella（トリン）]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 12:15:55 GMT</pubDate>
            <atom:updated>2023-08-31T01:29:32.873Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing is always an indispensable but also the most painful part of the software development process. It took me several hours to research in order to have a basic understanding to write a test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*i3gZBdrn_pk4PiyNahtm5Q.png" /></figure><p>Therefore, in this article, based on my experience, I would like to summarize how to write a basic integration test for Restful APIs in Spring Boot application.</p><h3><strong>I. What is Integration Test?</strong></h3><ul><li>As mentioned in the name, this type of testing mainly focuses on testing how the application works after integrating many layers together.</li><li>While unit tests are used to test each application’s component individually and independently, integration tests allow us to make sure the entire process is working as well as it should be.</li><li>Unlike unit tests, integration tests will use actual data and work exactly as its behavior in production mode. For that reason, we should distinguish the database used for integration tests.</li></ul><p><strong>Technologies that are used in this article’s example:</strong></p><ul><li>Java 17</li><li>Maven (3.8.1)</li><li>Spring Boot (3.0.6)</li><li>Spring Security (6.0.3)</li><li>JUnit 5</li><li>Liquibase (4.21.1)</li><li>MySQL (8.0.33)</li></ul><h3>II. How to implement Integration Testing</h3><h4>2.1. Maven Dependencies</h4><p>We’ll need to add some necessary dependencies:</p><pre>&lt;dependencies&gt;<br>  &lt;!-- Base dependencies --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;mysql&lt;/groupId&gt;<br>   &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;<br>   &lt;version&gt;${mysql.version}&lt;/version&gt;<br>  &lt;/dependency&gt;<br><br>&lt;!-- For testings --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>   &lt;exclusions&gt;<br>    &lt;exclusion&gt;<br>     &lt;groupId&gt;junit&lt;/groupId&gt;<br>     &lt;artifactId&gt;junit&lt;/artifactId&gt;<br>    &lt;/exclusion&gt;<br>   &lt;/exclusions&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>   &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h4>2.2. Configure MySQL Database</h4><p>As I mentioned above, we should prepare separate database for testing.</p><p>We’ll add one more configuration file named: <strong>application-test</strong>.yaml</p><pre>spring:<br>  datasource:<br>    driver-class-name: com.mysql.cj.jdbc.Driver<br>    url: jdbc:mysql://localhost:3306/database_test?characterEncoding=utf8&amp;allowPublicKeyRetrieval=true&amp;useSSL=false<br>    username: root<br>    password: root<br>  liquibase:<br>    change-log: classpath:db/changelog/master-log.xml</pre><p><em>* We’ll have another article to explain how to use Liquibase in details.</em></p><h4>2.3. Add JPA entities</h4><p>We assume that there will be three main entities: Accounts, Applicants and Job Posts.</p><p>a. Account entity</p><pre>package jp.co.example.integration.test.model;<br><br>import jakarta.persistence.*;<br>import jp.co.goalist.bext.enums.AccountType;<br>import lombok.*;<br>import org.hibernate.annotations.Cache;<br>import org.hibernate.annotations.CacheConcurrencyStrategy;<br>import org.hibernate.annotations.SQLDelete;<br>import org.hibernate.annotations.Where;<br><br>import java.time.LocalDateTime;<br><br>@Getter<br>@Setter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Builder<br>@Cacheable<br>@SQLDelete(sql = &quot;UPDATE accounts SET is_deleted = true WHERE id=?&quot;)<br>@Where(clause = &quot;is_deleted=false&quot;)<br>@Entity(name = &quot;accounts&quot;)<br>@Cache(region = &quot;accountCache&quot;, usage = CacheConcurrencyStrategy.READ_WRITE)<br>public class Account extends BaseEntity {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column<br>    private String fullName;<br><br>    @Column<br>    private String email;<br><br>    @Column<br>    private String password;<br><br>    @Column<br>    private String accountType;<br><br>    @Column<br>    private Long associatedId;<br><br>    @Column<br>    private LocalDateTime lastLoginDate;<br><br>    public AccountType getAccountType() {<br>        return this.accountType == null ? null : AccountType.fromValue(this.accountType);<br>    }<br><br>    public void setAccountType(AccountType accountType) {<br>        this.accountType = accountType == null ? null : accountType.getId();<br>    }<br>}</pre><p>b. Job Posts</p><pre>package jp.co.example.integration.test.model;<br>import jakarta.persistence.*;<br>import jp.co.goalist.bext.enums.EmploymentStatus;<br>import jp.co.goalist.bext.enums.ManuscriptStatus;<br>import jp.co.goalist.bext.enums.SalaryType;<br>import lombok.*;<br>import org.hibernate.annotations.Cache;<br>import org.hibernate.annotations.CacheConcurrencyStrategy;<br>import org.hibernate.annotations.SQLDelete;<br>import org.hibernate.annotations.Where;<br><br>import java.time.LocalDateTime;<br>import java.util.ArrayList;<br>import java.util.List;<br><br>@Getter<br>@Setter<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@ToString<br>@Cacheable<br>@SQLDelete(sql = &quot;UPDATE job_posts SET is_deleted = true WHERE id=?&quot;)<br>@Where(clause = &quot;is_deleted=false&quot;)<br>@Entity(name = &quot;job_posts&quot;)<br>@Cache(region = &quot;jobPostCache&quot;, usage = CacheConcurrencyStrategy.READ_WRITE)<br>public class JobPost extends BaseEntity {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String title;<br><br>    private String publicStatus;<br><br>    private String employmentStatus;<br><br>    @Column(columnDefinition = &quot;TEXT&quot;)<br>    private String introduction;<br><br>    @Column(columnDefinition = &quot;TEXT&quot;)<br>    private String summary;<br><br>    private String salaryType;<br><br>    private Integer minSalary;<br><br>    private Integer maxSalary;<br><br>    @Column(columnDefinition = &quot;TEXT&quot;, name = &quot;salary_matters&quot;)<br>    private String salaryMatter;<br><br>    private String totalClick;<br><br>    @OneToMany(mappedBy = &quot;post&quot;, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true)<br>    @ToString.Exclude<br>    private List&lt;Image&gt; images = new ArrayList&lt;&gt;();<br><br>    public ManuscriptStatus getPublicStatus() {<br>        return this.publicStatus == null ? null : ManuscriptStatus.fromValue(this.publicStatus);<br>    }<br><br>    public void setPublicStatus(ManuscriptStatus publicStatus) {<br>        this.publicStatus = publicStatus == null ? null : publicStatus.getId();<br>    }<br><br>    public SalaryType getSalaryType() {<br>        return this.salaryType == null ? null : SalaryType.fromValue(this.salaryType);<br>    }<br><br>    public void setSalaryType(SalaryType salaryType) {<br>        this.salaryType = salaryType == null ? null : salaryType.getId();<br>    }<br><br>    public void setEmploymentStatus(EmploymentStatus employmentStatus) {<br>        this.employmentStatus = employmentStatus == null ? null : employmentStatus.getId();<br>    }<br><br>    public EmploymentStatus getEmploymentStatus() {<br>        return this.employmentStatus == null ? null : EmploymentStatus.fromValue(this.employmentStatus);<br>    }<br>}</pre><p>c. Applicants</p><pre>package jp.co.example.integration.test.model;<br><br>import jakarta.persistence.*;<br>import jp.co.goalist.bext.enums.EmploymentStatus;<br>import jp.co.goalist.bext.enums.FinalEducation;<br>import jp.co.goalist.bext.enums.Gender;<br>import jp.co.goalist.bext.util.StringListConverter;<br>import lombok.*;<br>import org.hibernate.annotations.CacheConcurrencyStrategy;<br><br>import java.time.LocalDateTime;<br>import java.util.ArrayList;<br>import java.util.Date;<br>import java.util.List;<br><br>@Getter<br>@Setter<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@ToString<br>@Cacheable<br>@org.hibernate.annotations.Cache(region = &quot;applicantCache&quot;, usage = CacheConcurrencyStrategy.READ_WRITE)<br>@Entity(name = &quot;applicants&quot;)<br>public class Applicant extends BaseEntity {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column<br>    private String fullName;<br><br>    @Column<br>    private String hiraganaName;<br><br>    @Column<br>    private String email;<br><br>    @Column<br>    private String tel;<br><br>    @Column<br>    private String gender;<br><br>    @Column<br>    private Date birthday;<br><br>    @Column<br>    private String prefecture;<br><br>    @Column<br>    private String city;<br><br>    @Column<br>    private String employmentStatus;<br><br>    public void setEmploymentStatus(EmploymentStatus employmentStatus) {<br>        this.employmentStatus = employmentStatus == null ? null : employmentStatus.getId();<br>    }<br><br>    public EmploymentStatus getEmploymentStatus() {<br>        return this.employmentStatus == null ? null : EmploymentStatus.fromValue(this.employmentStatus);<br>    }<br><br>    public void setGender(Gender gender) {<br>        this.gender = gender == null ? null : gender.getId();<br>    }<br><br>    public Gender getGender() {<br>        return this.gender == null ? null : Gender.fromValue(this.gender);<br>    }<br>}</pre><h4>2.4. Add Controllers</h4><p>We’ll use OpenApi to generate the controller layers for Applicants and Job Posts.</p><p>a. ApplicantsApi.java</p><pre>@RequestMapping(&quot;/media&quot;)<br>@Generated(value = &quot;org.openapitools.codegen.languages.SpringCodegen&quot;, date = &quot;2023-07-20T10:18:56.531406500+07:00[Asia/Saigon]&quot;)<br>@Validated<br>@Tag(name = &quot;Applicant Pages&quot;, description = &quot;Applicant screen&quot;)<br>public interface ApplicantsApi {<br>/**<br>     * GET /applicants/profile : Get applicant&#39;s profile<br>     *<br>     * @return OK (status code 200)<br>     *         or Bad Validation (status code 400)<br>     *         or Unauthorized (status code 401)<br>     *         or Forbidden (status code 403)<br>     *         or Internal Server Error (status code 500)<br>     */<br>    @Operation(<br>            operationId = &quot;getApplicantProfile&quot;,<br>            summary = &quot;Get applicant&#39;s profile&quot;,<br>            tags = { &quot;Applicant Pages&quot; },<br>            responses = {<br>                    @ApiResponse(responseCode = &quot;200&quot;, description = &quot;OK&quot;, content = {<br>                            @Content(mediaType = &quot;application/json&quot;, schema = @Schema(implementation = DataResponse.class))<br>                    }),<br>                    @ApiResponse(responseCode = &quot;400&quot;, description = &quot;Bad Validation&quot;, content = {<br>                            @Content(mediaType = &quot;application/json&quot;, schema = @Schema(implementation = ErrorResponse.class))<br>                    }),<br>                    @ApiResponse(responseCode = &quot;401&quot;, description = &quot;Unauthorized&quot;, content = {<br>                            @Content(mediaType = &quot;application/json&quot;, schema = @Schema(implementation = ErrorResponse.class))<br>                    }),<br>                    @ApiResponse(responseCode = &quot;403&quot;, description = &quot;Forbidden&quot;, content = {<br>                            @Content(mediaType = &quot;application/json&quot;, schema = @Schema(implementation = ErrorResponse.class))<br>                    }),<br>                    @ApiResponse(responseCode = &quot;500&quot;, description = &quot;Internal Server Error&quot;, content = {<br>                            @Content(mediaType = &quot;application/json&quot;, schema = @Schema(implementation = ErrorResponse.class))<br>                    })<br>            }, security = {<br>                    @SecurityRequirement(name = &quot;Bearer&quot;)<br>            }<br>    )<br>    @RequestMapping(<br>            method = RequestMethod.GET,<br>            value = &quot;/applicants/profile&quot;,<br>            produces = { &quot;application/json&quot; }<br>    )<br>    @PreAuthorize(&quot;hasAuthority(&#39;APPLICANT&#39;)&quot;)<br>    ResponseEntity&lt;DataResponse&gt; _getApplicantProfile();<br>}</pre><p>b. ApplicantsApiController.java</p><pre>@Controller<br>@RequiredArgsConstructor<br>public class ApplicantsApiController implements ApplicantsApi {<br><br>    private static final Logger logger = LoggerFactory.getLogger(ApplicantsApiController.class);<br>    private final ApplicantService applicantService;<br><br>    @Override<br>    public ResponseEntity&lt;DataResponse&gt; _getApplicantProfile() {<br>        logger.info(&quot;_getApplicantProfile&quot;);<br>        return applicantService._getApplicantProfile();<br>    }<br>}</pre><p>c. JobPostsApi.java</p><pre>@RequestMapping(&quot;/media&quot;)<br>@Generated(value = &quot;org.openapitools.codegen.languages.SpringCodegen&quot;, date = &quot;2023-07-20T10:18:56.531406500+07:00[Asia/Saigon]&quot;)<br>@Validated<br>@Tag(name = &quot;Job Posts Pages&quot;, description = &quot;Job Posts screen&quot;)<br>public interface JobPostsApi {<br>/**<br>     * GET /jobPosts/{postId} : Display details of a job post<br>     *<br>     * @param postId 記事ID (required)<br>     * @param isClickCount クリック数を増やすかどうか  (optional, default to false)<br>     * @return OK (status code 200)<br>     *         or Internal Server Error (status code 500)<br>     */<br>    @Operation(<br>            operationId = &quot;getJobPostDetails&quot;,<br>            summary = &quot;Display details of a job post&quot;,<br>            tags = { &quot;Job Posts Pages&quot; },<br>            responses = {<br>                    @ApiResponse(responseCode = &quot;200&quot;, description = &quot;OK&quot;, content = {<br>                            @Content(mediaType = &quot;application/json&quot;, schema = @Schema(implementation = DataResponse.class))<br>                    }),<br>                    @ApiResponse(responseCode = &quot;500&quot;, description = &quot;Internal Server Error&quot;, content = {<br>                            @Content(mediaType = &quot;application/json&quot;, schema = @Schema(implementation = ErrorResponse.class))<br>                    })<br>            }<br>    )<br>    @RequestMapping(<br>            method = RequestMethod.GET,<br>            value = &quot;/jobPosts/{postId}&quot;,<br>            produces = { &quot;application/json&quot; }<br>    )<br>    ResponseEntity&lt;DataResponse&gt; _getJobPostDetails(<br>            @Parameter(name = &quot;postId&quot;, description = &quot;記事ID&quot;, required = true, in = ParameterIn.PATH) @PathVariable(&quot;postId&quot;) Long postId,<br>            @Parameter(name = &quot;isClickCount&quot;, description = &quot;クリック数を増やすかどうか &quot;, in = ParameterIn.QUERY) @Valid @RequestParam(value = &quot;isClickCount&quot;, required = false, defaultValue = &quot;false&quot;) Boolean isClickCount<br>    );<br>}</pre><p>d. JobPostApiController.java</p><pre>@Controller<br>@RequiredArgsConstructor<br>public class JobPostsApiController implements JobPostsApi {<br><br>    private static final Logger logger = LoggerFactory.getLogger(JobPostsApiController.class);<br>    private final JobPostService postService;<br><br>    @Override<br>    public ResponseEntity&lt;DataResponse&gt; _getJobPostDetails(Long postId, Boolean isClickCount) {<br>        logger.info(&quot;_getJobPostDetails, postId {} &quot;, postId);<br>        return postService.getJobPostDetails(postId, isClickCount);<br>    }<br>}</pre><h4>2.5. Add Services</h4><p>a. Accounts Service</p><pre>@Service<br>@RequiredArgsConstructor<br>public class AccountService {<br>    private final AccountRepository accountRepository;<br><br>    public Account getCurrentLoggedInUser() {<br>        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();<br>        if (Objects.isNull(authentication)) {<br>            throw new UnauthorizedException(ErrorMessage.UNAUTHORIZED_ERROR.getDescription());<br>        }<br>        String loggedInEmail = authentication.getName();<br>        return accountRepository.findEnabledAccountByEmail(loggedInEmail)<br>                .orElseThrow(() -&gt; new UnauthorizedException(<br>                        String.format(ErrorMessage.NOT_FOUND_ERROR.getDescription(),<br>                                &quot;現在のアカウント&quot;,<br>                                loggedInEmail)));<br>    }<br>}</pre><p>b. Applicants Service</p><pre>@Service<br>@RequiredArgsConstructor<br>public class ApplicantService {<br><br>    private final AccountService accountService;<br><br>    public ResponseEntity&lt;DataResponse&gt; _getApplicantProfile() {<br>        Account account = accountService.getCurrentLoggedInUser();<br>        Applicant applicant = getApplicantWithRelationsByAssociatedId(account.getAssociatedId());<br>        ApplicantProfileDto applicantProfileDto = APPLICANT_MAPPER.toProfileDto(applicant);<br>        return ResponseUtil.createDataResponse(applicantProfileDto, EntityName.APPLICANT);<br>    }<br>}</pre><p>c. Job Posts Service</p><pre>@RequiredArgsConstructor<br>@Service<br>public class JobPostService {<br>    private final JobPostRepository postRepository;<br><br>    protected JobPost getExistingPostById(Long postId) {<br>        Optional&lt;JobPost&gt; opPost= postRepository.findById(postId);<br>        if (opPost.isEmpty()) {<br>            throw new NotFoundException(ErrorResponse.builder()<br>                    .statusCode(ErrorMessage.NOT_FOUND_ERROR.getCode())<br>                    .message(String.format(<br>                            ErrorMessage.NOT_FOUND_ERROR.getDescription(),<br>                            EntityName.POST,<br>                            postId)).build());<br>        }<br>        return opPost.get();<br>    }<br><br>    public ResponseEntity&lt;DataResponse&gt; getJobPostDetails(Long postId) {<br>        JobPost jobPost = getExistingPostById(postId);<br>        JobPostDetailsDto jobPostDetails = JOB_POST_MAPPER.toJobPostDetailsDto(jobPost);<br>        jobPostDetails.setImages(getImages(jobPost.getImages()));<br>        return ResponseUtil.createDataResponse(jobPostDetails, EntityName.POST);<br>    }<br>}</pre><p><em>*We won’t go any deeper into the Repository layer in this article, so the code sample will stop at Service layer.</em></p><h4>2.6. Add Integration tests</h4><p>Before providing you code samples, I’m gonna note a few important things here.</p><blockquote><strong><em>***Important Notes:</em></strong></blockquote><ol><li>By convention, I often name my test classes as follows:</li></ol><blockquote>Unit tests: **SuccessUnitTest.java, **FailUnitTest.java</blockquote><blockquote>Integration tests: **SuccessIntegrationTest.java, **FailIntegrationTest.java</blockquote><p>2. Using <a href="https://junit.org/junit5/docs/5.4.1/api/org/junit/jupiter/api/Nested.html"><strong>@Nested</strong></a> to group all cases related to one API, the group name being the API method name.</p><blockquote>The reason is that when you are working on a large project, searching by API method name is really helpful.</blockquote><p>3. Using <a href="https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/executing-sql.html"><strong>@Sql</strong></a> to prepare test data. There are two levels that would be useful for integration tests.</p><ul><li><em>Class Level</em>: When <strong>@Sql</strong> is placed on the class name, it will run as <a href="https://junit.org/junit5/docs/5.0.2/api/org/junit/jupiter/api/BeforeAll.html"><strong>@BeforeAll</strong></a>, which means it executes once before all the test methods are executed. Depending on the specification of each project , we could use it to create default accounts for private APIs.</li><li><em>Method Level</em>: When <strong>@Sql</strong> is placed on method name, it will run as <a href="https://junit.org/junit5/docs/5.4.1/api/org/junit/jupiter/api/BeforeEach.html"><strong>@BeforeEach</strong></a>, which means it executes once before the test method runs.</li></ul><blockquote>* Remember to turn on <strong>Merge </strong>mode to run both levels; otherwise, method level will override the configuration on class level.</blockquote><pre>@SqlMergeMode(MERGE)</pre><p>4. Using <a href="https://docs.spring.io/spring-framework/reference/testing/annotations/integration-spring/annotation-activeprofiles.html"><strong>@ActiveProfiles</strong></a> to specify which configuration file to use when running tests</p><pre>@ActiveProfiles(&quot;test&quot;)</pre><p>5. Using <strong>@Transactional</strong> annotation to clean the data after each test execution. If you would like to have more controls on deleting data, you could use <a href="https://junit.org/junit5/docs/5.4.1/api/org/junit/jupiter/api/AfterEach.html"><strong>@AfterEach</strong></a> annotation instead.</p><blockquote>Be careful because <strong><em>LazyInitializationException </em></strong>error might happen when not using <strong>@Transactional.</strong></blockquote><p>6. Use <a href="https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/test-method.html"><strong>@WithUserDetails</strong></a> to simulate the security layer. In case you don’t want to handle login process and add access token manually to every private API call, you can come up with using this annotation.</p><p>_____________________________________________________</p><p>In this article, I have also prepared a simple test data as follows.</p><p>This file includes basic accounts and master data in the system used for all test cases.</p><pre>// initial_data_1.0_setup.sql<br>INSERT INTO `agencies`(id, `agency_name`,`created_date`,`updated_date`,`created_by`,`updated_by`)<br>VALUES (1, &quot;あいうえお株式会社&quot;, current_timestamp(), current_timestamp(), &quot;System&quot; , &quot;System&quot; );<br>INSERT INTO `agency_departments`(`id`, `agency_id`,`department_name`,`created_date`,`updated_date`,`created_by`,`updated_by`)<br>VALUES (1, 1,&quot;東京営業1&quot;, current_timestamp(), current_timestamp(), &quot;System&quot; , &quot;System&quot;);<br><br>INSERT INTO `accounts`<br>(`id`, `email`, `password`, `full_name`, `account_type`, `associated_id`, `department_id`, `is_temp_password`, `created_date`, `updated_date`, `created_by`, `updated_by`)<br>VALUES<br>(1, &quot;project_manager@gmail.com&quot;, &quot;$2a$10$lxSv6HOJL66LpCpcszDsj.hpZSBPUW2rNHNJqURzpplpJTAEMflka&quot;, &quot;クライアント&quot;, &quot;MANAGER&quot;, 1, 1, b&#39;0&#39;, current_timestamp(), current_timestamp(), &#39;System&#39; , &#39;System&#39;);<br><br>INSERT INTO `applicants`<br>(`id`, `full_name`, `hiragana_name`, `email`, `tel`, `gender`, `birthday`, `prefecture`, `city`,<br> `current_employment_status`, `created_date`, `updated_date`, `created_by`, `updated_by`)<br>VALUES<br>(1, &quot;青森 神社&quot;, &quot;ヤマモリ ジンジャ&quot;, &quot;applicant_001@gmail.com&quot;, &quot;080-3945-6778&quot;, &quot;FEMALE&quot;, &quot;1995-08-13&quot;, &quot;東京都&quot;, &quot;渋谷区&quot;,<br> &quot;CONTRACT&quot;, current_timestamp(), current_timestamp(), &#39;System&#39;, &#39;System&#39;);<br><br>INSERT INTO `accounts`<br>(`id`, `email`, `password`, `full_name`, `account_type`, `associated_id`, `department_id`, `is_temp_password`, `created_date`, `updated_date`, `created_by`, `updated_by`)<br>VALUES<br>(2, &quot;applicant_001@gmail.com&quot;, &quot;$2a$10$lxSv6HOJL66LpCpcszDsj.hpZSBPUW2rNHNJqURzpplpJTAEMflka&quot;, &quot;クライアント&quot;, &quot;APPLICANT&quot;, 1, NULL, b&#39;0&#39;, current_timestamp(), current_timestamp(), &#39;System&#39; , &#39;System&#39;);</pre><p>_____________________________________________________</p><p>For now, let’s create two test cases for success scenarios.</p><ol><li><strong>Public Restful API</strong></li></ol><p>In the given example above, we have one public URL which is <strong><em>/media/jobPosts/{postId}</em></strong></p><p>Since it’s public, anyone can make a call to this API.</p><p>a. Create new test class: <strong>JobPostControllerSuccessIntegrationTest</strong>.java</p><p>b. Prepare test data</p><p>This file includes special logical data for each API execution.</p><pre>// jobPosts_1.0_setup.sql<br>INSERT INTO `companies`(`id`, `company_code`, `catch_copy`, `summary`, `company_name`, `representative_name`, `created_date`, `updated_date`, `created_by`, `updated_by`)<br>VALUES (1, &quot;1504&quot;, &quot;アットホームな会社です&quot;, &quot;アットホームな会社です&quot;, &quot;あいうえお会社&quot;, &quot;田中一/中田仁&quot;, current_timestamp(), current_timestamp(), &#39;System&#39;, &#39;System&#39;);<br><br>INSERT INTO `company_locations`(`id`, `company_id`, `location_name`, `post_code`, `prefecture`, `city`, `home_address`, `tel`, `created_date`, `updated_date`, `created_by`, `updated_by`)<br>VALUES (1, 1, &#39;ABCビル&#39;, &#39;150-0031&#39;, &#39;東京都&#39;, &#39;渋谷区&#39;, &#39;桜丘町909-18&#39;, &#39;000-00000-000&#39;, NOW(), NOW(), &#39;SYSTEM&#39;, &#39;SYSTEM&#39;);<br><br>INSERT INTO `recruitment_manuscripts`(`id`, `title`,`public_status`,`small_occupation_id`,`employment_status`,`introduction`,`summary`,`job_description`,`total_click`,`location_id`,`is_deleted`,`created_date`,`updated_date`,`created_by`,`updated_by`)<br>VALUES (1, &#39;エンジニアの求人&#39;,&#39;PUBLIC&#39;,10,&#39;FULL_TIME&#39;,&#39;企業紹介&#39;,&#39;企業概要&#39;,&#39;求人内容&#39;,1,1,b&#39;0&#39;,NOW(),NOW(),&#39;SYSTEM&#39;,&#39;SYSTEM&#39;);<br><br>INSERT INTO `recruitment_manuscripts`(`id`, `title`,`public_status`,`small_occupation_id`,`employment_status`,`introduction`,`summary`,`job_description`,`total_click`,`location_id`,`is_deleted`,`created_date`,`updated_date`,`created_by`,`updated_by`)<br>VALUES (2, &#39;デザインの求人&#39;,&#39;PRIVATE&#39;,12,&#39;CONTRACT&#39;,&#39;企業紹介&#39;,&#39;企業概要&#39;,&#39;求人内容&#39;,1,1,b&#39;0&#39;,NOW(),NOW(),&#39;SYSTEM&#39;,&#39;SYSTEM&#39;);</pre><p>c. Add a success test case</p><pre>@Transactional<br>@ActiveProfiles(&quot;test&quot;)<br>@SqlMergeMode(MERGE)<br>@Sql(scripts = {&quot;/initial_data_1.0_setup.sql&quot;}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)<br>@SpringBootTest(classes = TestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)<br>@AutoConfigureMockMvc<br>@RequiredArgsConstructor<br>public class JobPostControllerSuccessIntegrationTest {<br><br>  @Autowired<br>  private JobPostRepository postRepository;<br><br>  @Nested<br>  @DisplayName(&quot;求人詳細を取得するAPI: _getJobPostDetails&quot;)<br>  class GetJobPostDetails {<br><br>    @Test<br>    @Sql(&quot;/jobPosts_1.0_setup.sql&quot;)<br>    @DisplayName(&quot;Test get job post details when isClickCount=true success&quot;)<br>    public void test_whenGetJobPostDetails_isClickCount_shouldReturn200() throws Exception {<br>        Long postId = 11L;<br>        MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.get(&quot;/media/manuscripts/&quot; + manuscriptId + &quot;?isClickCount=true&quot;)<br>                .contentType(MediaType.APPLICATION_JSON)<br>                .accept(MediaType.APPLICATION_JSON);<br>  <br>        MvcResult result = mockMvc<br>                .perform(mockRequest)<br>                .andExpect(status().isOk()).andReturn();<br>  <br>        String content = result.getResponse().getContentAsString((StandardCharsets.UTF_8));<br>        DataResponse dataResponse = objectMapper.readValue(content, DataResponse.class);<br>        JobPostDetailsDto actual = objectMapper.readValue(objectMapper.writeValueAsString(dataResponse.getData()), JobPostDetailsDto.class);<br>  <br>        assertEquals(200, result.getResponse().getStatus());<br>        assertEquals(String.format(SuccessMessage.GET_MSG.getDescription(), EntityName.POST), dataResponse.getMessage());<br>  <br>        assertEquals(postId, actual.getId());<br>        assertEquals(&quot;エンジニアの求人&quot;, actual.getTitle());<br>        assertEquals(&quot;Welcome to SBI&quot;, actual.getIntroduction());<br>        assertEquals(&quot;This is our job manuscript&quot;, actual.getSummary());<br>        assertEquals(&quot;FULL_TIME&quot;, actual.getEmploymentStatus());<br>        assertEquals(&quot;月給200000円〜月給500000円&quot;, actual.getSalary());<br>        Optional&lt;JobPost&gt; jobPost= postRepository.findById(postId);<br>        assert (jobPost).isPresent();<br>  <br>        assertEquals(2, jobPost.get().getTotalClick());<br>    }<br>  }<br>}</pre><p>2. <strong>Private Restful API</strong></p><p>In the given example above, we also have one private URL which is <strong><em>/media/applicants/profile</em></strong></p><p>Since it’s private, only logged in users of account type “APPLICANT” can call this API.</p><pre>@PreAuthorize(&quot;hasAuthority(&#39;APPLICANT&#39;)&quot;)</pre><p>a. Create new test class: <strong>ApplicantControllerSuccessIntegrationTest</strong>.java</p><p>b. Prepare test data set (Skipped since I don’t need more data here)</p><p>c. Simulate security layer</p><p>To do that, we’ll create a configuration file named: <strong>TestConfiguration</strong>.java</p><p>We will declare default accounts that simulate real users logged into the system.</p><pre>@org.springframework.boot.test.context.TestConfiguration<br>public class TestConfiguration {<br><br>    @Bean<br>    @Primary<br>    public UserDetailsService userDetailsService() {<br>        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();<br><br>        final User.UserBuilder userBuilder = User.builder().passwordEncoder(passwordEncoder::encode);<br>        List&lt;GrantedAuthority&gt; managerAuthorities = AuthorityUtils.createAuthorityList(&quot;MANAGER&quot;);<br>        List&lt;GrantedAuthority&gt; applicantAuthorities = AuthorityUtils.createAuthorityList(&quot;APPLICANT&quot;);<br><br>        UserDetails managerUser = userBuilder.username(&quot;project_manager@gmail.com&quot;).password(passwordEncoder.encode(&quot;password&quot;)).authorities(managerAuthorities).build();<br>        UserDetails applicantUser = userBuilder.username(&quot;applicant_001@gmail.com&quot;).password(passwordEncoder.encode(&quot;password&quot;)).authorities(applicantAuthorities).build();<br><br>        return new InMemoryUserDetailsManager(Arrays.asList(clientUser, agencyUser, saleUser, systemUser, applicantUser));<br>    }<br>}</pre><p>d. Add a success test case</p><pre>@ActiveProfiles(&quot;test&quot;)<br>@Sql(scripts = {&quot;/initial_data_1.0_setup.sql&quot;}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)<br>@SpringBootTest(classes = TestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)<br>@AutoConfigureMockMvc<br>@RequiredArgsConstructor<br>public class ApplicantControllerSuccessIntegrationTest {<br><br>  @Nested<br>  @DisplayName(&quot;応募者のプロファイルを取得するAPI: _getApplicantProfile&quot;)<br>  class GetApplicantProfile {<br>  <br>      @Test<br>      @WithUserDetails(&quot;applicant_001@gmail.com&quot;)<br>      @DisplayName(&quot;Test whether to get profile of APPLICANT successfully&quot;)<br>      public void test_whenGetApplicantProfile_byApplicant_shouldReturn200() throws Exception {<br>          MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.get(&quot;/media/applicants/profile&quot;)<br>                  .contentType(MediaType.APPLICATION_JSON)<br>                  .accept(MediaType.APPLICATION_JSON);<br>  <br>          MvcResult result = mockMvc<br>                  .perform(mockRequest)<br>                  .andExpect(status().isOk()).andReturn();<br>          String content = result.getResponse().getContentAsString(StandardCharsets.UTF_8);<br>          DataResponse dataResponse = objectMapper.readValue(content, DataResponse.class);<br>          ApplicantProfileDto actual = objectMapper.convertValue(dataResponse.getData(), ApplicantProfileDto.class);<br>  <br>          assertEquals(200, result.getResponse().getStatus());<br>          assertEquals(&quot;applicant_001@gmail.com&quot;, actual.getEmail());<br>          assertEquals(&quot;青森 神社&quot;, actual.getFullName());<br>          assertEquals(&quot;アオモリ ジンジャ&quot;, actual.getHiraganaName());<br>          assertEquals(&quot;1995/08/13&quot;, actual.getBirthday());<br>          assertEquals(&quot;東京都&quot;, actual.getPrefecture());<br>          assertEquals(&quot;渋谷区&quot;, actual.getCity());<br>          assertEquals(&quot;080-3945-6778&quot;, actual.getTel());<br>          assertEquals(Gender.FEMALE.getId(), actual.getGender());<br>          assertEquals(EmploymentStatusItemsDto.builder()<br>                  .id(EmploymentStatus.CONTRACT.getId())<br>                  .employmentStatusName(EmploymentStatus.CONTRACT.getName())<br>                  .build(), <br>                  actual.getEmploymentStatus());<br>      }<br>  }<br>}</pre><h3>III. Conclusion</h3><p>There is still much to discuss on how to write the tests. It varies depending on the specific project like test scenarios, how much data is enough for a test case, etc.</p><p>Besides knowing how to write tests, it’s better to understand how many test cases we should write to cover all possible scenarios . I’ll have another article to share about this topic later.</p><p>I hope you enjoyed this article. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5222c38ad3f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/integration-test-with-spring-boot-5222c38ad3f3">Integration Test with Spring Boot</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>