简体   繁体   中英

Mock embedded objects in integration test

Trying to write an integration test for a Spring application. Say i've got a class A which contains a class B object. Class B contains a class C object and I need to mock an object within this class for the integration test - any idea how i go about doing that without passing every object through as a parameter in the constructor?

eg

@Service
Class A {
    @Autowired
    private B b;

    public void testA() {
        B.testB();
    }
}

@Service
Class B {
    @Autowired
    private C c;

    public void testB() {
        c.testC();
    }
}

@Service
Class C {

    //External class pulled in from dependency library
    @Autowired
    private RestTemplate restTemplate;

    public void testC() {
        restTemplate.doSomethingInOutsideWorld();
    }
}

Integration test:

@RunWith(JUnitParamsRunner.class)
@SpringBootTest
public class MyIt {

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();


    @Mock
    private RestTemplate restTemplate;

    @Autowired
    private A a;

    @InjectMocks
    private C c;

    @Before
    public void setup() {
        initMocks(this);
    }

    @Test
    public void test1() throws IOException {
        a.testA()
    }
}

Doesn't mock the RestTemplate object, it tries to hit the outside world. Any advice on how to resolve this?

Achieve this by using SpringRunner and @MockBean

@RunWith(SpringRunner.class) is used to provide a bridge between Spring Boot test features and JUnit. Whenever we are using any Spring Boot testing features in out JUnit tests, this annotation will be required.

The @SpringBootTest annotation can be used when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.

Annotation that can be used to add mocks to a Spring ApplicationContext. Can be used as a class level annotation or on fields in either @Configuration classes, or test classes that are @RunWith the SpringRunner.

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyIt {

@MockBean
private RestTemplate restTemplate;

@Autowired
private A a;


@Before
public void setup() {
    initMocks(this);
}

@Test
public void test1() throws IOException {

    given(this.restTemplate.doSomethingInOutsideWorld()).willReturn(custom object);
    a.testA()
   }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM