I want to mock an object and one of its autowired constructor dependencies.
Eg:
class MyTest {
@MockBean A a;
@Test myTest() {
assertTrue(when(a.some()).thenCallRealMethod());
}
}
@Component
class A {
private B b;
A(B dependency) {
this.b = dependency;
}
boolean some() {
return b.value();
}
}
@Configuration
class B {
boolean value() { return true; }
}
This will throw a NPE when a::some
is called in MyTest::myTest
. How can I mock the mocks dependencies?
First, you have to choose the runner,
SpringRunner or Mockito Runner
In this case I chose SpringRunner: Docs : https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/junit4/SpringRunner.html
Then you created a MockBean of A and you have to define the mock behaviour
when(a.some()).thenReturn(true);
@RunWith(SpringRunner.class)
public class MyTest {
@MockBean A a;
@Test
public void myTest() {
when(a.some()).thenReturn(true);
assertTrue(a.some());
}
@Component
class A {
private B b;
A(B dependency) {
this.b = dependency;
}
boolean some() {
return b.value();
}
}
@Configuration
class B {
boolean value() { return true; }
}
}
Testing the Real method using @SpyBean:
@RunWith(SpringRunner.class)
@SpringBootTest(classes={MyTest.class,MyTest.B.class,MyTest.A.class})
public class MyTest {
@SpyBean A a;
@Test
public void myTest() {
assertTrue(a.some());
}
@Component
class A {
private B b;
A(B dependency) {
this.b = dependency;
}
boolean some() {
return b.value();
}
}
@Configuration
class B {
boolean value() { return true; }
}
}
Spying on A and mocking B would be like below :
@RunWith(SpringRunner.class)
@SpringBootTest(classes={MyTest.class,MyTest.B.class,MyTest.A.class})
public class MyTest {
@SpyBean A a;
@MockBean B b;
@Test
public void myTest() {
when(b.value()).thenReturn(false);
assertTrue(a.some());
}
@Component
class A {
private B b;
A(B dependency) {
this.b = dependency;
}
boolean some() {
return b.value();
}
}
@Configuration
class B {
boolean value() { return true; }
}
}
Result : Assertion failure as mocked behaviour of B is false.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.