Replace implementation of instantiated class without touching the code (java)

后端 未结 3 938
谎友^
谎友^ 2021-01-13 18:52

I have legacy code I don\'t want to touch.

public class LegacyCode{
    public LegacyCode() {
        Service s = new ClassA();
        s.getMessage();
    }         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-13 19:06

    The easier thing to do is to just create a ClassA in your test code. Declare it in the same package originally found in the actual code and use the same method names. Just make the method do nothing.

    For example, if your project structure looks like this:

    +- src
      +- main
        +- java
          +- com.company.code
            -- LegacyCode.java
            -- Service.java
          +- com.company.code.service
            -- ClassA.java
      +- test
        +- java
          +- com.company.code
            -- LegacyCodeTest.java
    

    Create an alternative ClassA under /src/test/java/com/company/code/:

    package com.company.code.service;
    /** Replaces the original implementation for testing purposes */
    public class ClassA implements Service{
        @Override
        public String getMessage() {
           return "I replaced the original implementation";
        }
    }
    

    Now your project structure will look like this:

    +- src
      +- main
        +- java
          +- com.company.code
            -- LegacyCode.java
            -- Service.java
          +- com.company.code.service
            -- ClassA.java
      +- test
        +- java
          +- com.company.code
            -- LegacyCodeTest.java
          +- com.company.code.service
            -- ClassA.java
    

    When your unit tests execute, the ClassA from your test folder will be loaded. This is way simpler than using a mock framework especially if your old code is messy, not dependency-injection-friendly and the actual ClassA is used everywhere.

    Just keep in mind that this sort of strategy can make your test code a bit more obscure, and you can't test the actual implementation of ClassA itself, nor easily provide alternative implementations for different test scenarios.

提交回复
热议问题