添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> 单元测试类 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 TestStrategy { @Autowired private ServiceStrategy serviceStrategy; @Test public void test() { serviceStrategy.sale("vip", "zhangsan"); serviceStrategy.sale("customer", "lisi"); } }
@SpringBootTest作用和@SpringBootApplication一样,扫描本包及子包
也可以写启动类
@SpringBootApplication
public class StartUpApplication {
public static void main(String[] args) {
SpringApplication.run(StartUpApplication.class, args);
}
}
在测试类添加
@SpringBootTest(classes = StartUpApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)