- Spring Boot Testing
- 依赖:spring-boot-starter-test
- Junit、Spring Test、AsserrtJ
- Test Case
- 要求:保证测试方法的独立性。
- 步骤:初始化数据、执行测试代码、验证测试结果、清理测试数据。
- 常用注解:
--- @BeforeClass:在类启动前调用
--- @AfterClass:在类结束后调用
--- @Before:在测试方法启动前调用
--- @After:在测试方法启动后调用
SpringBootTests
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.service.DiscussPostServiceImpl;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class SpringBootTests {
@Autowired
private DiscussPostServiceImpl discussPostService;
private DiscussPost data;
@BeforeClass
public static void beforeClass(){
System.out.println("beforeClass");
}
@AfterClass
public static void afterClass(){
System.out.println("afterClass");
}
@Before
public void before(){
System.out.println("before");
//初始化测试数据
data=new DiscussPost();
data.setUserId(111);
data.setTitle("Test Title");
data.setContent("Test Content");
data.setCreateTime(new Date());
discussPostService.addDiscussPost(data);
}
@After
public void after(){
System.out.println("after");
//删除测试数据
discussPostService.updateStatus(data.getId(),2);
}
@Test
public void test1(){
System.out.println("test1");
}
@Test
public void test2(){
System.out.println("test2");
}
@Test
public void testFindById(){
DiscussPost post = discussPostService.selectDiscussPostById(data.getId());
Assert.assertNotNull(post);
Assert.assertEquals(data.getTitle(),post.getTitle());
Assert.assertEquals(data.getContent(),post.getContent());
}
@Test
public void testUpdateScore(){
int rows = discussPostService.updateScore(data.getId(), 2000.00);
Assert.assertEquals(1,rows);
DiscussPost post = discussPostService.selectDiscussPostById(data.getId());
Assert.assertEquals(2000.00,post.getScore(),2);
}
}