我有一个Spring Boot web应用程序,我通过运行这个类来启动它。。。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
该web应用程序有一个由Spring MVC控制器提供的JSP/HTML前端,该控制器与服务通信,该服务与使用Hibernate向MySQL数据库读取/写入实体的DAO通信。
所有组件和服务都被实例化,@Autowired和web应用程序运行良好。
现在,我想构建JUnit测试,并测试服务或DAO中的一些功能。
我开始编写下面这样的JUnit测试,但很快就陷入了不知道如何实例化所有@Autowired组件和类的困境。
public class MySQLTests {
@Test
public void test000() {
assertEquals("Here is a test for addition", 10, (7+3));
}
@Autowired
UserService userService = null;
@Test
public void test001() {
userService.doSomething("abc123");
// ...
}
}
我基本上希望web应用程序启动并运行,然后让JUnit测试运行这些服务中的方法。
我需要一些帮助才能开始。。。有没有类似于@SpringBootApplication注释的JUnit可以在我的JUnit类中使用?
回答我自己的问题。。。我让它像这样工作。。。
-
用注释测试类
@RunWith(SpringRunner.class)
@SpringBootTest
-
测试类必须位于@Controller类之上的包中。。。所以我的测试类是
com.projectname.*
,控制器是com.projectname.controller.*
工作代码如下。。。
package com.projectname;
import static org.junit.Assert.assertNotNull;
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;
import com.projectname.controller.WebController;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {
@Autowired
private WebController controller;
@Test
public void contextLoads() throws Exception {
assertNotNull("WebController should not be null", controller);
}
}