Spring-boot实例学习之 Command line application单元测试

引入依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <optional>true</optional>
</dependency>

创建单元测试类

创建Junit测试类,并用到 @RunWith,@SpringBootTest两个注解。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {StartupRunner.class})
public class UserEntityTestTest {

  @Autowired
  private JunitService mockService;
  
  @Test
  public void test1() throws Exception {
    junitService.printJunitServiceName();
  }
}


@SpringBootApplication
public class StartupRunner implements CommandLineRunner {

  @Override
  public void run(String... strings) throws Exception {
    System.out.println("hello CommandLineRunner");
  }

  public static void main(String[] args) {
    SpringApplication.run(StartupRunner.class, args);
  }
}

@SpringBootTest 标注一个测试类,如果该注解没有指定加载的启动配置类,那么会自动搜索标注有@SpringBootApplication注解的类。如果需要手工指定,那么通过注解的classes属性即可。找到启动类后注入服务,随后可以进行测试。

创建Mock

通过@MockBean注解字段,通过BDDMockito的方法生成模拟接口的返回值或抛出的异常,然后进行测试。

@RunWith(SpringRunner.class)

@SpringBootTest(classes = {StartupRunner.class})
public class UserEntityTestTest {

  @MockBean
  private JunitService mockService;

  @Test
  public void test1() throws Exception {
    BDDMockito.given(mockService.printMsg()).willReturn("hello");

    String msgRet = mockService.printMsg();

    Assert.assertTrue(msgRet.equals("hello"));
  }

}

参考

41.3 Testing Spring Boot applications
http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值