尝试为 Spring 应用程序编写集成测试。假设我有一个 A 类,其中包含一个 B 类对象。 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
对象,它会尝试访问外部世界。关于如何解决这个问题有什么建议吗?
最佳答案
通过使用SpringRunner
和@MockBean
来实现这一点
@RunWith(SpringRunner.class) 用于在 Spring Boot 测试功能和 JUnit 之间提供桥梁。每当我们在 JUnit 测试中使用任何 Spring Boot 测试功能时,都需要此注释。
当我们需要引导整个容器时,可以使用@SpringBootTest注解。该注释通过创建将在我们的测试中使用的 ApplicationContext 来工作。
可用于向 Spring ApplicationContext 添加模拟的注释。可以用作类级别注释,也可以用于 @Configuration 类中的字段,或 @RunWith 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()
}
}
关于java - 在集成测试中模拟嵌入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55185210/