Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created April 17, 2020 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdkosher/d6f5064fd8ed441f7b0e6f7929960b2e to your computer and use it in GitHub Desktop.
Save bdkosher/d6f5064fd8ed441f7b0e6f7929960b2e to your computer and use it in GitHub Desktop.

Say I've got a controller class, that effectively delegates to a service, retrieves some domain objects, and converts them to another data type that better serializes to JSON and contains some additional metadata.

@Data 
public class RawFoo {
  private long id;
  private String name;
}

@Data
public class CookedFoo {
  private long id;
  private String name;
  private boolean first;
  private boolean last;
}

@RestController
@RequiredArgsConstructor
public class FooController {

  private FooService
  
  @GetMapping
  public List<CookedFoo> allFoo() {
    List<RawFoo> raw = service.allFoo();
    
  }

}

Here's the situation: I want to set the first and last only when the particular foos have names. Otherwise, I want them to be false.

Problem: I want to partially mock the service so that I can test the controller's ability to set these first and last attributes but at the same time I don't want to be burdened with the hassle of instantiating the controller manually. The controller has lots of dependencies and just mocking a single one is a pain.

I also don't want to make the dependencies mutalbe. I like the fact that they're constructor injected and want to keep it that way.

So the question is, how can I write certain tests that mock specific dependencies but leave the rest the same, while other tests use the legit Spring-wired class?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment