LogoLogo
diffblue.comFree trial
  • Discover Diffblue Cover
  • Get Started
    • What is Diffblue Cover?
    • Get started
      • Free trial
      • Get started - Cover Plugin
      • Get started - Cover CLI
      • Get started - Cover Pipeline
      • Get started - Cover Reports
    • Specs & Reqs
    • Reference Deployments
    • Licensing
      • Online license activation
      • Offline license activation
      • Diffblue License Manager
    • Update Cover
    • FAQs
    • Diffblue Learning
      • Get started
        • Just the basics
        • Free trial
        • Cover Plugin (IDE)
        • Cover CLI (Command Line)
      • Developer
        • Unit tests (IDE)
        • Unit tests (CLI)
        • Test coverage
      • DevOps
        • GitHub
        • GitLab
        • Other CI
      • Administrator
        • Admin - IntelliJ
        • Admin - CLI
        • Admin - Reports
      • Test coverage
        • Developer
        • Senior developer
        • Cover Reports Administrator
  • EVALUATION & ONBOARDING
    • Proof of Value
    • Jumpstart
      • Prerequisites for onboarding
      • Phase 1: Up and running
        • Module 1: Create your Cover unit test baseline
        • Module 2: Cover Pipeline CI integration
      • Phase 2: Developer productivity
        • Module 3: Getting started using Cover
        • Module 4: Introduction to Cover Reports
      • Phase 3: Advanced topics
        • Module 5: Speed up your test execution
        • Module 6: Getting more from Cover
  • Features
    • Cover Plugin
      • Writing tests
        • Gutter icons
        • Menu options
        • Run configurations
        • Cover Plugin tool window
        • Test Review
        • Test examples
        • Creating partial tests
        • Creating skeleton tests
        • Covering all enum values
        • Test insertion order
        • Diffblue Sandbox
        • Environment Check Cache
      • Project configuration
        • General dependencies
        • Test framework dependencies
      • Cover Plugin settings
        • Test Naming
        • Test Formatting
        • Spring configuration options
        • Method Annotations
        • Test Directory
        • Reset Cover Plugin settings
      • Cover Plugin admin
        • Core Maintenance
        • Cover Plugin toolbar menu
        • Cover Plugin status bar widget
        • Telemetry
        • Memory management
        • Using SonarQube with Cover Plugin
        • Log files
        • Troubleshooting
    • Cover CLI
      • Writing tests
        • Command summary
        • Test examples
        • Creating partial tests
        • Customizing test inputs
        • Customizing test setup
        • Test naming
        • Test formatting
        • Test insertion order
        • Patch files
        • Diffblue Sandbox
        • Operational behaviors
        • Test validation
      • Project configuration
        • Preflight checks
        • General dependencies
        • Test framework dependencies
        • Compiling your project successfully
          • Building a Maven project
          • Building a Gradle project
        • Configuring Cover to work with your project's build system
          • Quick guide
          • Configuration file in detail
          • Getting Started with Ant Projects
          • Default configuration
        • Mocking using Mockito
        • Spring profiles
        • Runtime environment
      • Commands & Arguments
        • Environment configuration for CI
        • Packages, classes, and methods
        • Quoting command line arguments
        • Argument files
      • Cover CLI admin
        • Core Maintenance
        • Telemetry
        • Memory management
        • Using Cover CLI in Eclipse
        • Using SonarQube with Cover CLI
        • Log files
        • Troubleshooting
      • Environment Configuration
    • Cover Pipeline
      • Cover Pipeline for CI
        • Quick Start - General
        • Quick Start - Jenkins
        • Quick Start - Azure Pipelines
        • Quick Start - AWS Codebuild
        • Integrating Diffblue Cover into CI on pull requests
        • Installation - VMs or CI run
      • Cover Pipeline for GitLab
        • Introduction
        • Installation and initial setup
        • GitLab workflow
        • Configuration
        • Troubleshooting
        • Related topics
      • Cover Pipeline for GitHub
        • Introduction
        • Installation and initial setup
        • GitHub workflow
        • Configuration
        • Troubleshooting
        • Related topics
    • Cover Reports
      • Cover Reports Contributor
        • Java project config (JaCoCo)
        • Generate and upload reports bundles
        • Authenticated uploads
      • Cover Reports User
        • Navigation
        • Dashboards
        • Telemetry data
        • Export API
        • Considerations
      • Cover Reports Administrator
        • Install and update Cover Reports
        • Configuration options
        • Database backup
        • SSO with Cover Reports
        • Uninstall Cover Reports
    • Cover Optimize
      • Get started - Cover Optimize
      • Cover Optimize & Gradle
      • Cover Optimize & Maven
      • Patch files
    • Cover Refactor
      • Get started - Cover Refactor
    • Cover Annotations
      • Mocking Annotations
      • Custom Input Annotations
      • Interesting Value Annotations
    • Output Codes
      • E - Environment Codes
      • L - License Codes
      • R - Reason Codes
      • T - Testability Codes
      • V - Validation Codes
      • Working with output codes
        • Working with code E020
        • Working with codes E057 to E065
        • Working with code E085
        • Working with code R005
        • Working with code R006
        • Working with code R008
        • Working with code R011
        • Working with code R012
        • Working with code R013
        • Working with code R026
        • Working with code R031
        • Working with code V003
    • Tutorials
      • How to measure test quality
      • How to improve code coverage
      • How to test a new feature
      • How to find regressions
      • How to use Diffblue Cover in test driven development (TDD)
      • How to write tests for Kotlin projects
      • Examples of tests created by Diffblue Cover
      • Best practices for testing private methods
  • Updates & Upgrades
    • Update Cover
    • Cover Editions
    • What's new
    • Release archive
      • 2025-05-01
      • 2025-04-02
      • 2025-04-01
      • 2025-03-02
      • 2025-03-01
      • 2025-02-02
      • 2025-02-01
      • 2025-01-02
      • 2025-01-01
      • 2024-12-02
      • 2024-12-01
      • 2024-11-02
      • 2024-11-01
      • 2024-10-02
      • 2024-10-01
      • 2024-09-02
      • 2024-09-01
      • 2024-08-02
      • 2024-08-01
      • 2024-07-04
      • 2024-07-03
      • 2024-07-01
      • 2024-06-02
      • 2024-06-01
      • 2024-05-02
      • 2024-05-01
      • 2024-04-02
      • 2024-04-01
      • 2024-03-02
      • 2024-03-01
      • 2024-02-02
      • 2024-02-01
      • 2024-01-02
      • 2024-01-01
      • 2023-12-02
      • 2023-12-01
      • 2023-11-03
      • 2023-11-02
      • 2023-11-01
      • 2023-10-02
      • 2023-10-01
      • 2023-09-02
      • 2023-09-01
      • 2023-08-02
      • 2023-08-01
      • 2023-07-03
      • 2023-07-02
      • 2023-07-01
      • 2023-06-02
      • 2023-06-01
      • 2023-05-02
      • 2023-05-01
      • 2023-04-02
      • 2023-04-01
      • 2023-03-02
      • 2023-03-01
      • 2023-02-02
      • 2023-02-01
      • 2023-01-02
      • 2023-01-01
      • 2022-12-02
      • 2022-12-01
      • 2022-11-02
      • 2022-11-01
      • 2022-10-03
      • 2022-10-02
      • 2022-10-01
      • 2022-09-02
      • 2022-09-01
      • 2022-08-05
      • 2022-08-03
      • 2022-08-02
      • 2022-08-01
      • 2022-07-02
      • 2022-07-01
      • 2022-06-02
      • 2022-06-01
      • 2022-05-02
      • 2022-05-01
      • 2022-04-02
      • 2022-04-01
      • 2022-03-02
      • 2022-03-01
      • 2022-02-02
      • 2022-02-01
      • 2022-01-02
      • 2022-01-01
      • 2021-06-02
      • 2021-02-01
  • Legal
    • Diffblue Legal
      • Diffblue End User License Agreement (EULA)
      • Cover Third Party Notices and/or Licenses
      • Privacy Notice
Powered by GitBook
On this page
  • Basic assertions
  • Mocking
  • OS agnostic assertions
  • Example containing logic
  • Example of complex logic
  • Testing trivial methods

Was this helpful?

Export as PDF
  1. Features
  2. Cover Plugin
  3. Writing tests

Test examples

In this topic we show both the input source code, and the tests written by Diffblue Cover, for code of varied complexity, accompanied by a detailed narrative to help you further understand tests created by Diffblue Cover.


Basic assertions

This is a simple example of Spring Service source code with a trivial getter. Cover can write a Spring Boot test for the getter in a service provider by inlining Arrange, Act, and Assert.

Source

import org.springframework.stereotype.Service;

@Service
public class SimpleService
{
  public String getValue() {
    return "a really simple service";
  }
}

Test written by Diffblue Cover

@SpringBootTest
@RunWith(org.springframework.test.context.junit4.SpringRunner.class)
public class SimpleServiceDiffblueTest {
  @Autowired
  private SimpleService simpleService;
  @Test
  public void diffbluetestGetValue() {
    // Arrange, Act and Assert
    assertEquals("a really simple service", this.simpleService.getValue());
  }
}

Mocking

This is a class that contains two methods to upload and download a file to/from an Amazon S3 bucket. As the Amazon S3 bucket is a cloud storage mechanism, the test for this class/methods requires dependency injection. Cover can mock these types of dependencies and tests downloadFileFromBucket method by asserting the expected S3Object and the downloaded S3Object using the method.

Source

@Service
public class AmazonService {

  @Autowired
  private AmazonS3 s3client;

  public PutObjectResult uploadFileToBucket(String bucketName, String key, File file) {
    return s3client.putObject(bucketName, key, file);
  }

  public S3Object downloadFileFromBucket(String bucketName, String key) {
    return s3client.getObject(bucketName, key);
  }
}

Tests written by Diffblue Cover

@SpringBootTest
public class AmazonServiceDiffblueTest {
  @MockBean
  private AmazonS3Client amazonS3Client;
  @Autowired
  private AmazonService amazonService;
  @Test
  public void diffbluetestUploadFileToBucket() {
    // Arrange
    PutObjectResult putObjectResult = new PutObjectResult();
    putObjectResult.setContentMd5("file-hash");
    when(this.amazonS3Client.putObject(or(isA(String.class), isNull()), or(isA(String.class), isNull()),
        or(isA(File.class), isNull()))).thenReturn(putObjectResult);

    // Act and Assert
    assertSame(putObjectResult, this.amazonService.uploadFileToBucket("foo", "foo",
        Paths.get(System.getProperty("java.io.tmpdir"), "test.txt").toFile()));
  }
  @Test
  public void diffbluetestDownloadFileFromBucket() throws UnsupportedEncodingException {
    // Arrange
    StringInputStream objectContent = new StringInputStream("file-name");
    S3Object s3Object = new S3Object();
    s3Object.setObjectContent(objectContent);
    when(this.amazonS3Client.getObject(or(isA(String.class), isNull()), or(isA(String.class), isNull())))
        .thenReturn(s3Object);

    // Act and Assert
    assertSame(s3Object, this.amazonService.downloadFileFromBucket("foo", "foo"));
  }
}

OS agnostic assertions

This example returns time in a different format. Cover writes a test to assert date and time that is not dependent on operating system or local time zones.

Source

public class TimeInAliceWonderland {

  private static final String DODO_DATETIME_FORMAT = "ss:mm:HH dd-MMM-yyyy";

  public static String reformatDodoDateTime(Date humanDate) {
    Map<String, DateFormat> dateFormatMap = new HashMap<>();
    dateFormatMap.put(DODO_DATETIME_FORMAT, new SimpleDateFormat(DODO_DATETIME_FORMAT));
    return dateFormatMap.get(DODO_DATETIME_FORMAT).format(humanDate);
  }
}

Test written by Diffblue Cover

@Test
  public void diffbluetestReformatDodoDateTime() {
    LocalDateTime atStartOfDayResult = LocalDate.of(1970, 1, 1).atStartOfDay();
    assertEquals("00:00:00 01-Jan-1970", TimeInAliceWonderland
        .reformatDodoDateTime(
            Date.from(atStartOfDayResult.atZone(ZoneId.systemDefault()).toInstant())));
  }

Example containing logic

In this example, Cover writes two tests to cover each pathway through the conditional - a test which adds 10 to the balance and asserts the new balance should be 20 and a second test where the account is closed.

Source

public class Account {
  private final long accountNumber;
  private final Client client;
  private long currentBalance;
  private String accountName;
  private AccountState accountState;

  public Account(final long accountNumber, final Client client, final long amount) {
    this.accountNumber = accountNumber;
    this.client = client;
    currentBalance = amount;
    accountName = "Current";
    accountState = AccountState.OPEN;
  }

  public long getCurrentBalance() {
    return currentBalance;
  }

  public void addToBalance(final long amount) throws AccountException {
    if (getAccountState() != AccountState.OPEN) {
      throw new AccountException("Cannot add to balance, account is closed.");
    }
    currentBalance += amount;
  }

Test written by Diffblue Cover

 @Test
  public void diffbluetestAddToBalance() throws AccountException {
    // Arrange
    Account account = new Account(1234567890L, new Client("Carlos Welch"), 10L);

    // Act
    account.addToBalance(10L);

    // Assert
    assertEquals(20L, account.getCurrentBalance());
  }

Example of complex logic

This example code has three branches - Cover covers 100% of branches and creates three tests for three cases using existing enum values.

Source

public class VirtualSnackCupboard {

  public static Snack whatCanISnackNow(int oClock) {
    if (oClock == 10) {
      return Snack.CHOCOLATE;
    } else if (oClock == 15) {
      return Snack.CAKES;
    } else {
      return Snack.VEGGIE;
    }
  }
  enum Snack {VEGGIE, CHOCOLATE, CAKES}
}

Tests written by Diffblue Cover

  public void diffbluetestPickSnack() {
    assertEquals(VirtualSnackCupboard.Snack.CHOCOLATE, VirtualSnackCupboard.whatCanISnackNow(10));
    assertEquals(VirtualSnackCupboard.Snack.CAKES, VirtualSnackCupboard.whatCanISnackNow(15));
    assertEquals(VirtualSnackCupboard.Snack.VEGGIE, VirtualSnackCupboard.whatCanISnackNow(0));
  }

Testing trivial methods

Diffblue Cover CLI deliberately does not test trivial methods such as getters, setters, constructors and factory methods to avoid creating large quantities of noisy tests that do not contribute to overall coverage. There isn't a benefit to be gained from testing these trivial methods directly as, for example, getters and setters simply access attributes so there is no actual logic to be tested. Similarly, constructors and factory methods also contain little or no logic. If Diffblue Cover CLI did test such methods directly, a minor coverage increase might be gained, but this "improvement" would be meaningless in terms of improving code quality.

Ultimately these trivial methods will be covered when Cover generates tests for other methods that call these trivial methods. Diffblue recommends improving the percentage of coverage using the many options within the product, as shown in the Commands & Arguments topic.

PreviousTest ReviewNextCreating partial tests

Last updated 1 year ago

Was this helpful?