【发布时间】:2019-03-19 15:55:02
【问题描述】:
假设我有一个包含几个 Spring bean 的测试配置,它们实际上是模拟的,我想在 JUnit 测试套件中指定这些模拟的行为。
@Profile("TestProfile")
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = {
"some.cool.package.*"})
public class IntegrationTestConfiguration {
@Bean
@Primary
public Cool cool() {
return Mockito.mock(Cool.class);
}
}
// ...
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ActiveProfiles("TestProfile")
public class CoolIntegrationTest {
private final Cool cool;
@Autowired
public CoolIntegrationTest(Cool cool) {
this.cool = cool;
}
@Test
public void testCoolBehavior {
when(cool.calculateSomeCoolStuff()).thenReturn(42);
// etc
}
}
如果我运行这个测试,我会得到:
java.lang.Exception: Test class should have exactly one public zero-argument constructor
我知道在测试中使用 Autowired 字段等解决方法,但我想知道是否有办法在 JUnit 测试中使用 Autowired 注释?
【问题讨论】:
标签: java spring junit integration-testing autowired