Java 集成测试中的模拟嵌入式对象
正在尝试为Spring应用程序编写集成测试。假设我有一个类a,它包含一个类B对象。类B包含一个C类对象,我需要在这个类中模拟一个对象以进行集成测试——知道我如何在不将每个对象作为构造函数中的参数传递的情况下进行模拟吗 e、 g 集成测试:Java 集成测试中的模拟嵌入式对象,java,spring,mockito,Java,Spring,Mockito,正在尝试为Spring应用程序编写集成测试。假设我有一个类a,它包含一个类B对象。类B包含一个C类对象,我需要在这个类中模拟一个对象以进行集成测试——知道我如何在不将每个对象作为构造函数中的参数传递的情况下进行模拟吗 e、 g 集成测试: @RunWith(JUnitParamsRunner.class) @SpringBootTest public class MyIt { @ClassRule public static final SpringClassRule SPRI
@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()
}
}
不模拟
restemplate
对象,它试图攻击外部世界。关于如何解决这个问题有什么建议吗?使用SpringRunner
和@MockBean
@RunWith(SpringRunner.class)用于在Spring启动测试功能和JUnit之间提供桥梁。每当我们在out JUnit测试中使用任何Spring启动测试功能时,都需要此注释。
@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()
}
}
当我们需要引导整个容器时,可以使用@SpringBootTest注释。注释通过创建将在我们的测试中使用的ApplicationContext来工作。
@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()
}
}
注释,可用于向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()
}
}