1 springboot单元测试
1.1 spring-boot-starter-test
我再真正需要单元测试的是什么呢,是否应该是service层呢?因为如果是controller,app启动通过yapi
进行接口管理或者postman来做接口测试不是也可以吗?
但是,如果要登录呢?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
import com.dzmsoft.qingqiu.base.pojo.BaZi;
import com.dzmsoft.qingqiu.rule.dto.ShyGenYinDto;
import com.dzmsoft.qingqiu.rule.service.impl.QiangRuoService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class QiangRuoServiceTest {
@Autowired
private QiangRuoService qiangRuoService;
@Test
public void getShyDto(){
BaZi bazi = new BaZi.Builder()
.setYear("乙丑").setMonth("甲申").setDay("戊子").setHour("戊午")
.build();
ShyGenYinDto dto = qiangRuoService.getShyDto(bazi);
System.out.println(dto.getYz());
}
}
出现这个问题,在QingQiuApplication
启动类增加@ComponentScan(basePackages = {"com.dzmsoft"})
包的扫描即可。
AopAutoConfiguration matched:
- @ConditionalOnClass found required classes 'org.springframework.context.annotation.EnableAspectJAutoProxy', 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice', 'org.aspectj.weaver.AnnotatedElement'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
- @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)
下图是postman的调用
1.2 无需web环境
我只想测试一下组件中service的逻辑是否正确。
@RunWith(SpringRunner.class)
@SpringBootTest(classes =TestApplication.class, webEnvironment= SpringBootTest.WebEnvironment.NONE)
public class WhcaDemo {
@Autowired
private WhcaService whcaService;
@Test
public void test1(){
System.out.println("hello world");
}
这里还必须指定一个TestApplication.class
,否则会报错
@SpringBootApplication
@ComponentScan(basePackages = {"com.whty"})
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class,args);
}
}
放在test目录下即可