3 Star 6 Fork 5

jarchan / spring-test-examples

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
chapter_1_s2_spring_testing.md 3.82 KB
一键复制 编辑 原始数据 按行查看 历史
jarchan 提交于 2017-08-24 16:53 . refactor

Chapter 1: 基本用法 - 使用Spring Testing工具

既然我们现在开发的是一个Spring项目,那么肯定会用到Spring Framework的各种特性,这些特性实在是太好用了,它能够大大提高我们的开发效率。那么自然而然,你会想在测试代码里也能够利用Spring Framework提供的特性,来提高测试代码的开发效率。这部分我们会讲如何使用Spring提供的测试工具来做测试。

例子1

源代码见FooServiceImplTest

@ContextConfiguration(classes = FooServiceImpl.class)
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {

  @Autowired
  private FooService foo;

  @Test
  public void testPlusCount() throws Exception {
    assertEquals(foo.getCount(), 0);

    foo.plusCount();
    assertEquals(foo.getCount(), 1);
  }

}

在上面的源代码里我们要注意三点:

  1. 测试类继承了AbstractTestNGSpringContextTests,如果不这么做测试类是无法启动Spring容器的
  2. 使用了[@ContextConfiguration][javadoc-ContextConfiguration]来加载被测试的Bean:FooServiceImpl
  3. FooServiceImpl@Component

以上三点缺一不可。

例子2

在这个例子里,我们将@Configuration作为nested static class放在测试类里,根据@ContextConfiguration的文档,它会在默认情况下查找测试类的nested static @Configuration class,用它来导入Bean。

源代码见FooServiceImplTest

@ContextConfiguration
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {

  @Autowired
  private FooService foo;

  @Test
  public void testPlusCount() throws Exception {
    assertEquals(foo.getCount(), 0);

    foo.plusCount();
    assertEquals(foo.getCount(), 1);
  }

  @Configuration
  @Import(FooServiceImpl.class)
  static class Config {
  }

}

例子3

在这个例子里,我们将@Configuration放到外部,并让@ContextConfiguration去加载。

源代码见Config

@Configuration
@Import(FooServiceImpl.class)
public class Config {
}

FooServiceImplTest

@ContextConfiguration(classes = Config.class)
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {

  @Autowired
  private FooService foo;

  @Test
  public void testPlusCount() throws Exception {
    assertEquals(foo.getCount(), 0);

    foo.plusCount();
    assertEquals(foo.getCount(), 1);
  }

}

需要注意的是,如果@Configuration是专供某个测试类使用的话,把它放到外部并不是一个好主意,因为它有可能会被@ComponentScan扫描到,从而产生一些奇怪的问题。

参考文档

Java
1
https://gitee.com/chanjarster/spring-test-examples.git
git@gitee.com:chanjarster/spring-test-examples.git
chanjarster
spring-test-examples
spring-test-examples
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891