java - Spring:在 Junit 中加载的类中 Autowiring 不同的类

标签 java spring junit autowired

我在 Spring 中有以下场景:

public class ClassA{

@Autowired
private ClassB classB;
}

我在我的测试类中使用(更准确地说是 Autowiring )ClassA。但是我想做的是只为我的 Junit 修改 ClassB,所以当 ClassA 在我的测试类中 Autowiring 时,它会加载修改后的 ClassB(而不是原来的)。

有办法实现吗?

最佳答案

如果没有 Bean 配置,想不出另一种方法来做到这一点。 您可以通过两种方式进行配置:

首先:

@Configuration
public class AppConfig {

  @Bean
  public ClassB classB() {
    return new ClassB() {
      // this is a subclass that inherits everything from ClassB, so override what you want here
    }
  }
}

第二个:(取自 here)

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

  // do this if you only want the modified classB in 1 place
  @Configuration
  static class TestConfig {
      @Bean
      public ClassB classB () {
          return new ClassB() {
            // same as the first
          }
      }
  }

  @Test
  public void testMethod() {
    // test
  }
}

最后,您可以在主文件夹中创建一个新接口(interface) ClassBClassBImpl,在测试文件夹中创建一个新接口(interface) ClassBTestImpl。您仍然需要使用其中一种配置。

关于java - Spring:在 Junit 中加载的类中 Autowiring 不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46923461/

相关文章:

java - 关于 AbstractApplicationContext.getBeansOfType() 和 getBean() 的问题

java.util.Date 来自<输入类型 ="datetime-local"/>

java - ActiveProfile 在 Junit5 测试中不起作用

spring - 未找到 REST CXF 和 Spring cxf-extension-jaxrs-binding 文件异常?

java - jdbcTemplate.getDataSource() 在我的单元测试中始终为 null

java - 如何在 NetBeans 中创建库

java - Google Guice 和 Servlet

java - 为具有两个 When 语句的测试获取 WrongTYpeOfReturnValue

groovy - JMockit - 期望中的模拟方法不返回结果

java - 用于创建按钮数组的循环无法在 JPanel 中正确显示