代码之家  ›  专栏  ›  技术社区  ›  maloney

集成测试中的模拟嵌入对象

  •  0
  • maloney  · 技术社区  · 7 年前

    尝试为Spring应用程序编写集成测试假设我有一个包含B类对象的a类B类包含一个C类对象,我需要为集成测试模拟这个类中的一个对象-知道我如何在不将每个对象作为构造函数中的参数传递的情况下完成这项工作吗?

    例如

    @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();
        }
    }
    

    集成测试:

    @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()
        }
    }
    

    不会嘲笑 RestTemplate 对象,它试图攻击外部世界关于如何解决这个问题有什么建议吗?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Ryuzaki L    7 年前

    通过使用 SpringRunner 和 @MockBean

    @runwith(springrunner.class)用于在spring boot测试特性和junit之间提供一个桥梁。每当我们在out-JUnit测试中使用任何Spring引导测试特性时,都需要这个注释。

    当我们需要引导整个容器时,可以使用@SpringBootTest注释注释通过创建将在我们的测试中使用的applicationContext来工作。

    可用于向Spring ApplicationContext添加模拟的注释可以用作类级注释,也可以用于@configuration类中的字段,或者使用springrunner的@run测试类。

    @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()
       }
    }