简体   繁体   English

Spring:在 Junit 中加载的类中自动装配不同的类

[英]Spring: Autowire different class inside of a class loaded in Junit

I have the following scenario in Spring :我在 Spring 中有以下场景:

public class ClassA{

@Autowired
private ClassB classB;
}

I'm using (Autowiring to be more precise) ClassA in my Test class.我在我的测试类中使用(更精确的自动装配) ClassA But what I'd like to do somehow is to modify ClassB just for my Junit, so with that, When ClassA is autowired in my test class, it loads the modified ClassB (instead of the original one).但是我想以某种方式做的是仅为我的 Junit 修改ClassB ,因此,当ClassA在我的测试类中自动装配时,它会加载修改后的ClassB (而不是原来的ClassB )。

Is there a way to achive that?有没有办法做到这一点?

Can't think of another way to do this without Bean Configuration.如果没有 Bean 配置,想不出另一种方法来做到这一点。 You can configure this in 2 ways:您可以通过两种方式进行配置:

First:第一的:

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

Second: (taken from 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
  }
}

Finally, you could create a new interface ClassB and ClassBImpl in your main folder and ClassBTestImpl in your test folder.最后,您可以在主文件夹中创建新接口ClassBClassBImpl ,并在测试文件夹中ClassBTestImpl You still need to use one of the configuration.您仍然需要使用其中一种配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM