stk1234
stk1234

Reputation: 1126

How Can I Mock 1 Dependency and Autowire the Other?

I have 2 dependencies in my controller: a validator and a repository. For this particular test, I'd like to mock the validator, but keep the repository (for now). In previous versions of my code, my controller only had 1 dependency (the repository) and a test setup like so seemed to automatically wire in the correct repository.

@Autowired
CreateShortUrlController createShortUrlController;

When I introduced the validator dependency, I changed my test setup to the following

@Autowired
UrlRepository repository;

@Mock
UrlValidator urlValidator = new UrlValidator();

CreateShortUrlController createShortUrlController = new CreateShortUrlController(repository, urlValidator);

Now, when I run my tests, it says my repository is null. Is there anything I can do to retain the "magic" of grabbing the right repository while mocking the other dependency?

Upvotes: 0

Views: 769

Answers (2)

Lesiak
Lesiak

Reputation: 26094

You need to get familiar with @MockBean, and use it (instead of @Mock) to make spring context aware of your mocked beans.

@Autowired
CreateShortUrlController createShortUrlController;

@MockBean
UrlValidator urlValidator;

Upvotes: 1

Yiao SUN
Yiao SUN

Reputation: 978

You should use @InjectMock with your CreateShortUrlController and use @Spy with UrlRepository and @Mock with UrlValidator

@InjectMocks
CreateShortUrlController createShortUrlController;

@Spy
UrlRepository repository;

@Mock
UrlValidator urlValidator;

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    this.repository = new UrlRepository();
    this.createShortUrlController = new CreateShortUrlController(repository, urlValidator);
}

But you may need think of the dessin of your application and make sure if you need test your UrlRepository here or in infrastructure layer

Upvotes: 0

Related Questions