DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Spring Boot: JUnit Integration Test
  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services
  • Using ZK With Spring Boot
  • Develop Web Application With Spring Boot in 30 minutes

Trending

  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  • Navigating Change Management: A Guide for Engineers
  • How to Introduce a New API Quickly Using Micronaut
  • Memory-Optimized Tables: Implementation Strategies for SQL Server
  1. DZone
  2. Coding
  3. Frameworks
  4. Mocking Files for JUnit Testing a Spring Boot Web Application on Synology NAS

Mocking Files for JUnit Testing a Spring Boot Web Application on Synology NAS

You can use a Spring Boot application to perform JUnit testing on NAS — learn how to build such a web app in this tutorial.

By 
Marc Vanbrabant user avatar
Marc Vanbrabant
·
May. 17, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
26.7K Views

Join the DZone community and get the full member experience.

Join For Free

For a Spring Boot application which will check backup files on a Synology RS815+ NAS, we wanted to be able to easily test the files stored on this NAS, without having to copy the 7TB that were stored on it.

Ideally, we wanted to create the same file structure to use the web application in a Spring development profile, as well as use these file structures in a JUnit test.

Introducing FileStructureCreator

We started by creating a new class FileStructureCreator which looks like this:

@Getter
@Setter
public class FileStructureCreator implements Closeable {

  public static final Path baseTestPath = Paths.get("testFiles");
  private Path fileStructureBasePath;

  public static FileStructureCreator create(Path file) {
      return createStructure(file, false);
  }

  public static FileStructureCreator createTempDirectory(Path file) {
      return createStructure(file, true);
  }

  @SneakyThrows
  private static FileStructureCreator createStructure(Path file, boolean createTempDirectory) {
      FileStructureCreator fileStructureCreator = new FileStructureCreator();

      if (!Files.exists(baseTestPath)) {
          Files.createDirectory(baseTestPath);
      }

      String path = baseTestPath.toString() + (createTempDirectory ? "/" + UUID.randomUUID().toString() : "")
              + "/";
      Path basePath = Paths.get(path);
      fileStructureCreator.setFileStructureBasePath(basePath);
      FileUtils.forceMkdir(basePath.toFile());

      try (Stream<String> stream = Files.lines(file)) {
          stream.forEach(line -> {
              Metadata fileMetaData = Metadata.from(line);

              Path fileEntry = Paths.get(path + fileMetaData.getWindowsSafeFilename());
              try {
                  FileUtils.forceMkdir(fileEntry.getParent().toFile());
                  if (!Files.exists(fileEntry)) {
                      Files.write(fileEntry, line.getBytes());
                      Files.setLastModifiedTime(fileEntry, FileTime.from(fileMetaData.getModificationTime()));
                  }
              } catch (IOException ignore) {
                  throw new RuntimeException("Exception creating directory: " + fileEntry.getParent());
              }
          });
      }
      return fileStructureCreator;
  }
  @Override
  @SneakyThrows
  public void close() {
      if (fileStructureBasePath != null) {
          FileUtils.deleteDirectory(fileStructureBasePath.toFile());
      }
  }
}

This basically creates the whole directory structure and the necessary files. We just need to pass it a base file which holds the metadata of the file structure.

The metadata holds a timestamp, file size and the path for this file. It looks like this:

2016-04-05T10:30:15.012345678 5120
backupftp/@eaDir/sharesnap_share_configuration/SYNO@.quota

2018-02-26T00:00:09.012345678 169

backupftp/@eaDir/sharesnap_share_configuration/share_configuration


On our Synology NAS, we can then easily generate a file with the whole tree structure of a (specific) directory by executing this command:

find backupftp -type f -printf
"%TY-%Tm-%TdT%TH:%TM:%.12TS\t%s\t%p\n">test/backupftp.files.txt

Copy the generated file from your Synology NAS to your project.

In a JUnit test we use the FileStructureCreator class like in the example below. Note that FileStructureCreatorimplements AutoCloseable, so we can use a try/catch block to clean up the files after the test completes.

@Value("classpath:/TestDiskConsistencyPolicy-notEnoughFileSets.txt")
private Path notEnoughFileSets;

@Test(expected = RuntimeException.class)
public void backupSetWithNoFileSetsThrowException() {
  try( FileStructureCreator creator = FileStructureCreator.createTempDirectory(notEnoughFileSets) ) {
      BackupSet backupSet = BackupSet.builder().uri(creator.getFileStructureBasePath().toString()).build();
      new DiskConsistencyPolicy(backupSet).execute();
      assertTrue( "Expecting a RuntimeException here", false);
  }
}

For the Spring Boot application, we just define a @Configuration class which will create the data structures for our file shares as defined on the Synology NAS.

@Configuration
@Profile("dev")
public class TestFilesInstaller {
  @Bean
  public FileStructureCreator ftpFiles(@Value("classpath:/backupftp.files.txt") Path file) {
      return FileStructureCreator.create(file);
  }
  @Bean
  public FileStructureCreator nfsFiles(@Value("classpath:/backupnfs.files.txt") Path file) {
      return FileStructureCreator.create(file);
  }
}

Because they are defined as a @Bean, the close() method will automatically be called when the application shuts down, removing all files from disk when the Spring Boot application is stopped.

Just…don’t run the dev profile in production; I’ll let you figure out what happens.

In the future, we'll show you how to build a backup checker and how to monitor and verify backups on your NAS.

Spring Framework Web application Spring Boot JUnit

Published at DZone with permission of Marc Vanbrabant. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot: JUnit Integration Test
  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services
  • Using ZK With Spring Boot
  • Develop Web Application With Spring Boot in 30 minutes

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!