spring java调用testng,Spring、Spring Boot和TestNG测试指南 - 使用Spring Testing工具

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

例子1

@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);

}

}

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

使用了@ContextConfiguration来加载被测试的Bean:FooServiceImpl

FooServiceImpl是@Component

以上三点缺一不可。

例子2

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

@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去加载。

@Configuration

@Import(FooServiceImpl.class)

public class Config {

}

@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扫描到,从而产生一些奇怪的问题。

参考文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值