Let's use the following as an example.
@Autowired
@MockBean
private Foo foobar;
Does the Spring Context load the class Foo
first, and then apply the mock? Or does the @Mockbean
get detected somehow, and Spring creates and applies the mock instead of loading the class Foo
into the Spring Context. I have a suspicion that it is the latter, but I would like confirmation.
Spring will throw an exception.
Let's define the class Foo.
@Component
public class Foo {
public Foo() {
System.out.println("I am not a mock");
}
}
Whenever testing using @Autowired
, spring injects an instance of Foo and the constructor will print "I am not a mock"
, as in the code below.
@SpringBootTest(classes = Main.class)
@RunWith(SpringRunner.class)
public class FooTest {
@Autowired
Foo foo;
@Test
public void test() {
System.out.println(foo);
}
}
On the other hand, using @MockBean, spring will not create the real bean and the message in the constructor will not be printed. This scenario is represented by the following code.
@SpringBootTest(classes = Main.class)
@RunWith(SpringRunner.class)
public class FooTest {
@MockBean
Foo foo;
@Test
public void test() {
System.out.println(foo);
}
}
However, when you try to use both annotations together, spring will throw a BeanCreationException
caused by an IllegalStateException
. It means that the field foo cannot have an existing value. This scenario will happen in executing the code below:
@SpringBootTest(classes = Main.class)
@RunWith(SpringRunner.class)
public class FooTest {
// this will not work
@Autowired
@MockBean
Foo foo;
@Test
public void test() {
System.out.println(foo);
}
}
And the stack trace will be something like:
org.springframework.beans.factory.BeanCreationException: Could not inject field: com.tbp.Foo com.FooTest.foo; nested exception is java.lang.IllegalStateException: The field com.tbp.Foo com.FooTest.foo cannot have an existing value
at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.inject(MockitoPostProcessor.java:413) ~[spring-boot-test-1.5.2.RELEASE.jar:1.5.2.RELEASE]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With