Spring/Spring Test
Spring Test : Integration Test
Korean Eagle
2020. 8. 4. 12:11
728x90
1. 아래의 코드는 JUnit 4를 기반한 코드이다.
2. 통합 테스트의 경우 실제 컨텍스트가 필요하기 때문에 @SpringBootTest가 필요하다.
2-1 @RunWith만으로는 전체 스프링 컨텍스트가 기동하지 않기 때문에 Service가 주입되지 않는다.
3. 테스트 컨텍스트를 기동하기 위하여 @RunWith(SpringRunner.class) 가 필요하다.
3-1 없으면 테스트용 컨텍스트가 생성되지 않아 기동 자체가 되지 않는다.
4. testSaveOfDescpriton 테스트의 @Transactional은 필수다.
4-1 없는 경우, 스프링 컨텍스트 밖에서 실행하므로 Session을 찾을 수가 없다.
package pe.pilseong.recipe.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.transaction.Transactional;
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 pe.pilseong.recipe.command.RecipeCommand;
import pe.pilseong.recipe.coverter.RecipeCommandToRecipe;
import pe.pilseong.recipe.coverter.RecipeToRecipeCommand;
import pe.pilseong.recipe.domain.Recipe;
import pe.pilseong.recipe.repository.RecipeRepository;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RecipeServiceIT {
public static final String DESCRPTION = "DESCRIPTION";
@Autowired
RecipeService recipeService;
@Autowired
RecipeRepository recipeRepository;
@Autowired
RecipeCommandToRecipe recipeConverter;
@Autowired
RecipeToRecipeCommand commandConverter;
@Test
@Transactional
public void testSaveOfDesription() {
//given
Iterable<Recipe> recipes = recipeRepository.findAll();
Recipe testRecipe = recipes.iterator().next();
RecipeCommand testRecipeCommand = commandConverter.convert(testRecipe);
//when
testRecipeCommand.setDescription(DESCRPTION);
Recipe savedRecipe = recipeService.save(testRecipeCommand);
//then
assertEquals(DESCRPTION, savedRecipe.getDescription());
assertEquals(testRecipe.getId(), savedRecipe.getId());
}
}728x90