2

I have a Spring application where I am using EasyMock for mocking in JUnit tests.

I have three classes (let's say A and B and C) defined below.

@Named("A")
@Primary
public class A {
}

@Named("B")
public class B extends A {
}

public class C {
  @Inject
  private A a; // It should inject A instance here since it is marked as primary
}


public class CTest {

@Mock
private A a;// Here I'm getting exception
}

When I run tests in CTest class, I'm getting error expected single matching bean but found 2:(A and B).

Why @primary annotation is not working here.

Prateek Sharma
  • 109
  • 2
  • 9
  • Usually Profile work together with Bean annotation. Can you try it instead of Name? – Qingfei Yuan Jun 04 '19 at 15:23
  • Very similiar to a question i asked a while back. See if this helps: https://stackoverflow.com/questions/50607285/spring-boot-testconfiguration-not-overriding-bean-during-integration-test – The Head Rush Jun 04 '19 at 15:34

1 Answers1

1

Looks like you might need below config.

spring.main.allow-bean-definition-overriding=true

If overriding is for test only, you can try it in the test profile.

ref - https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1-Release-Notes#bean-overriding

Shree Harsha S
  • 665
  • 7
  • 14