Hypertest v2 Docs
HyperTest
  • Overview
    • How It Works?
  • SETUP GUIDE
    • Installation
      • Deploy HyperTest Server
      • Creating your first User
      • Adding your first service
      • Integrate SDK
        • Node.js
          • Node.js SDK with CJS
          • Node.js SDK with ESM
        • Java
    • Start a Test Run
      • CLI Login
      • Type References
      • Java
  • Interpreting Test Results
    • Test Results
    • Understanding Results Categories
    • Mock Not Found
    • AI Match Mocks
    • Accepting Changes
  • USER GUIDES
    • Node.js SDK
      • Limit memory usage
      • Supported NPM packages
      • Mock Dependencies Manually
      • Unmocking/Passing Through
      • Sampling and blocking requests
      • Manage Global Variables
      • Mocking Environment Variables
      • Tags
      • Set HTTP path patterns
      • Discard a test case(Request) while recording
      • Set Git Commit Hash
      • Code coverage based features
        • Continuous Coverage
        • Updating test coverage
        • Running post test deduplication
        • Only testing modified requests
        • Ignore differences for unmodified requests
      • Experimental flags
      • Manual Request
      • Only testing modified requests
      • Server hooks
    • Java SDK
      • Sampling and blocking requests
      • Mock Dependencies Manually
      • Tags
      • Unmocking/Passing Through
      • Code Coverage Setup and Report Generation
      • Supported Java packages
    • Build your own Docker Image
    • CLI Config
    • Ignoring Differences
      • Type References for Filter functions
  • Impact Features
    • Fast Mode
    • Code Coverage Report
    • Delete Recorded Requests
    • Inter Service Testing
  • Release History
    • Slack Integration
    • Version History
Powered by GitBook
On this page
  1. USER GUIDES
  2. Java SDK

Mock Dependencies Manually

PreviousSampling and blocking requestsNextTags

Last updated 2 months ago

HyperTest provides a way for you to manually mock certain dependencies that are not instrumented automatically. Allows you to capture mocks with a readable input, which will help you better understand the mocks on the dashboard.

Please check the list of , before proceeding with manual mocks.

These mocks also come in handy when you want to reduce false positives in the test reports caused by a utility that returns arbitrary values e.g., timestamps, and UUIDs.

Let's look at an example where manual mocks can be utilized.

Below is an API route that generates PROMO code for a user.

@RestController
@RequestMapping("/api")
public class PromoCodeController {

    @Autowired
    private UserRepository userRepository;

    // Generate promo code based on userId
    private String generatePromoCode(Long userId) {
        String uniquePart = UUID.randomUUID().toString().split("-")[0]; // Take the first part of a UUID
        return "PROMO-" + uniquePart + "-" + userId;
    }

    @PostMapping("/generate_promo_code")
    public ResponseEntity<?> generatePromoCode(@RequestBody UserRequest userRequest) {
        // Retrieve user from the database using emailId
        User user = userRepository.findByEmailId(userRequest.getEmailId());

        if (user == null) {
            return ResponseEntity.status(404).body("User not found");
        }

        // Generate promo code
        String promoCode = generatePromoCode(user.getId());

        return ResponseEntity.ok(new PromoCodeResponse(promoCode));
    }
}

If we record this API interaction and run a Test then HyperTest will report a value-modified error, but this is a false positive and it's not a real change that was made in the logic.

To eliminate this recurrent issue we can manually mock the generation of the Promo code. When we re-record this API interaction we will also have the exact value of the Promo code that was generated and the same will be used in the Test.

@RestController
@RequestMapping("/api")
public class PromoCodeController {

    @Autowired
    private UserRepository userRepository;

    // Generate promo code based on userId
    @HtManualMock(configClass = GeneratePromoCodeConfig.class)
    private String generatePromoCode(Long userId) {
        String uniquePart = UUID.randomUUID().toString().split("-")[0]; // Take the first part of a UUID
        return "PROMO-" + uniquePart + "-" + userId;
    }

    @PostMapping("/generate_promo_code")
    public ResponseEntity<?> generatePromoCode(@RequestBody UserRequest userRequest) {
        // Retrieve user from the database using emailId
        User user = userRepository.findByEmailId(userRequest.getEmailId());

        if (user == null) {
            return ResponseEntity.status(404).body("User not found");
        }

        // Generate promo code
        String promoCode = generatePromoCode(user.getId());

        return ResponseEntity.ok(new PromoCodeResponse(promoCode));
    }
    
    public class GeneratePromoCodeConfig implements HtManualMockConfig {
        @Override
        public String generateIdentifier(Object... functionArgs) throws Exception {
            return "generatePromoCode";
        }
        
        @Override
        public EnumManager.FunctionTypeEnum getFunctionType() {
            return EnumManager.FunctionTypeEnum.SYNC;
        }
        
        @Override
        public Object[] normalizeArguments(Object... functionArgs) {
            return functionArgs;
        }
    }
}

To create a manual mock you need to follow these steps:

  • Add annotation: Add an annotation (@HtManualMock) above the method you want to manually mock. This annotation accepts an argument called configClass.

  • Create a config class: Create a config class for this mock. This class must implement HtManualMockConfig interface. You have to implement 2 mandatory methods and 1 optional method:

    • generateIdentifier(Object ...args): It accepts the same arguments as originalFn. It should return a string which will be your unique identifier (An identifier is needed to pick the right mock during REPLAY, if you are making the same kind of function calls then consider adding a number to the identifier).

    • getFunctionType(): It should return an ENUM (EnumManager.FunctionTypesEnum). It tells us that that method you are trying to manually mock is a SYNC/ASYNC/CALLBACK method.

    • normalizeArguments(Object... args): This method is optional and normalizes or transforms the input arguments. It accepts the same arguments as originalFn and returns an object with normalized input values. Return value of this function will be used as readableInput and would be used for display on dashboard.

If we run a test with the manual mock in place it passes.

automatically instrumented packages