java - 在 Spring 中使用 mockito 测试更大的服务
问题描述
我开始学习 mockito 来测试我的课程。我知道如何用一个,也许是 2 个模拟小班来做到这一点,但是当我的服务更大时,我遇到了问题。例如,我有服务
public class ShoppingListService {
Map<Ingredient, Long> shoppingList = new HashMap<>();
List<MealInfo> meals = new ArrayList<>();
UserInfoService userInfoService;
DietMealsService dietMealsService;
UserRepository userRepository;
User user;
@Autowired
public ShoppingListService(UserInfoService userInfoService, DietMealsService dietMealsService,UserRepository userRepository) {
this.userInfoService = userInfoService;
this.dietMealsService = dietMealsService;
this.userRepository = userRepository;
}
public Map<Ingredient,Long> createShoppingList(){
user = userRepository.findByLoginAndPassword(userInfoService.getUser().getLogin(),userInfoService.getUser().getPassword()).get();
shoppingList.clear();
meals.clear();
meals = user.getDiet().getMeals();
meals=dietMealsService.adjustIngredients(meals);
for (MealInfo meal : meals) {
meal.getMeal().getIngredients().forEach(s -> {
if(shoppingList.containsKey(s.getIngredient()))
shoppingList.put(s.getIngredient(), s.getWeight()+shoppingList.get(s.getIngredient()));
else
shoppingList.put(s.getIngredient(),s.getWeight());
});
}
return shoppingList;
}
}
我想测试方法createShoppingList
。
我应该创建几个实例并模拟除 shoppingList 和餐点之外的每个字段,然后创建 1 或 2 个成分、餐点和使用后的实例 -> 然后像这样?
@Test
public void createShoppingList() {
//GIVEN
Ingredient pineapple = new Ingredient().builder().name("Pineapple").caloriesPer100g(54F).carbohydratePer100g(13.6F).fatPer100g(0.2F).proteinPer100g(0.8F).build();
Ingredient watermelon = new Ingredient().builder().name("Watermelon").caloriesPer100g(36F).carbohydratePer100g(8.4F).fatPer100g(0.1F).proteinPer100g(0.6F).build();
IngredientWeight pineappleWithWeight...
//after this create Meal, MealInfo, Diet...
}
在其他类之下:
public class MealInfo implements Comparable<MealInfo>{
@Id
@GeneratedValue
private Long id;
private LocalDate date;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "meal_id")
private Meal meal;
private String name;
@ManyToMany(cascade = CascadeType.REMOVE)
@JoinTable(name = "diet_meal_info", joinColumns = @JoinColumn(name = "meal_info_id"),
inverseJoinColumns = @JoinColumn(name = "diet_id"))
private List<Diet> diet;
public MealInfo(LocalDate date, String description, Meal meal) {
this.date = date;
this.name = description;
this.meal = meal;
}
@Override
public int compareTo(MealInfo o) {
return getName().compareTo(o.getName());
}
}
public class Meal {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "meal_ingredient", joinColumns = @JoinColumn(name = "meal_id"),
inverseJoinColumns = @JoinColumn(name = "ingredient_id"))
private List<IngredientWeight> ingredients;
@Column(length = 1000)
private String description;
private String imageUrl;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "meal_category", joinColumns = @JoinColumn(name = "meal_id"),
inverseJoinColumns = @JoinColumn(name = "category_id"))
private Set<Category> category;
@OneToMany(mappedBy = "meal", cascade = CascadeType.ALL, orphanRemoval = true)
private List<MealInfo> mealInfo;
private Integer calories;
public Meal(MealForm mealForm) {
this.name = mealForm.getName();
this.description = mealForm.getDescription();
this.imageUrl = mealForm.getImageUrl();
this.category = mealForm.getCategory();
}
}
public class IngredientWeight {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(name = "ingredient_weight_id")
private Ingredient ingredient;
private Long weight;
@ManyToMany
@JoinTable(name = "meal_ingredient", joinColumns = @JoinColumn(name = "ingredient_id"),
inverseJoinColumns = @JoinColumn(name = "meal_id"))
private Set<Meal> meals;
}
public class Ingredient {
@Id
@GeneratedValue
private Long id;
private String name;
@Column(name = "calories")
private Float caloriesPer100g;
@Column(name = "proteins")
private Float proteinPer100g;
@Column(name = "carbohydrates")
private Float carbohydratePer100g;
@Column(name = "fat")
private Float fatPer100g;
@OneToMany(mappedBy = "ingredient", cascade = {CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE},
fetch = FetchType.EAGER)
private List<IngredientWeight> ingredientWeights;
}
你能写出如何测试这个方法或测试实现吗?或者你有没有像这样测试更大方法的公共存储库?
解决方案
如前所述,您可能不希望在您的服务中使用 fields 和user
。这些字段使服务在多线程环境中使用不安全,例如 Web 应用程序或 Web 服务(可以由多个客户端访问,因此多个线程同时访问)。例如,如果另一个线程进入,您正在处理的可能会在进程中途被清除。相反,暂时将这些字段设为方法内的局部变量。如果逻辑变得太复杂并且您的服务太大,您可以将其提取到单独的服务或帮助类中,该类在方法调用开始时实例化并在结束时丢弃。shoppingList
meals
shoppingList
createShoppingList
createShoppingList
我总是将单元测试编写为单个类的白盒测试。如果可以的话,我会尝试覆盖代码中的每个分支。您可以通过在 IntelliJ 中运行具有覆盖率的测试来检查这一点。请注意,黑盒测试也非常有用,它们专注于组件的“契约”。在我看来,单元测试通常不适合这种情况,因为单个类的契约通常对组件的整体功能不是很感兴趣,并且如果重构代码很容易改变。我将集成(或端到端)测试编写为黑盒测试。这需要设置一个存根应用程序环境,例如内存数据库,可能还需要通过 WireMock 提供一些外部服务。如果您对此感兴趣,请查看 Google 的合同测试或 RestAssured 框架。
关于您的代码的一些说明:
public Map<Ingredient,Long> createShoppingList() {
// if any of the chained methods below return null, a NullPointerException occurs
// You could extract a method which takes the userInfoService user as an argument, see `findUser` below.
user = userRepository.findByLoginAndPassword(userInfoService.getUser().getLogin(),userInfoService.getUser().getPassword()).get();
// the above would then become:
User user = findUser(userInfoService.getUser()).orElseThrow(new ShoppingServiceException("User not found");
// instead of clearing these field, just initialize them as local variables:
shoppingList.clear();
meals.clear();
meals = user.getDiet().getMeals();
// I would change adjustIngredients so it doesn't return the meals but void
// it's expected that such a method modifies the meals without making a copy
meals = dietMealsService.adjustIngredients(meals);
// I would extract the below iteration into a separate method for clarity
for (MealInfo meal : meals) {
// I would also extract the processing of a single meal into a separate method
// the `meal.getIngredients` actually doesn't return Ingredients but IngredientWeights
// this is very confusing, I would rename the field to `ingredientWeights`
meal.getMeal().getIngredients().forEach(s -> {
// I would replace the four calls to s.getIngredient() with one call and a local variable
// and probably extract another method here
// You are using Ingredient as the key of a Map so you must implement
// `equals` and // `hashCode`. Otherwise you will be in for nasty
// surprises later when Java doesn't see your identical ingredients as
// equal. The simplest would be to use the database ID to determine equality.
if(shoppingList.containsKey(s.getIngredient()))
shoppingList.put(s.getIngredient(), s.getWeight()+shoppingList.get(s.getIngredient()));
else
shoppingList.put(s.getIngredient(),s.getWeight());
});
}
return shoppingList;
}
private Optional<User> findUser(my.service.User user) {
if (user != null) {
return userRepository.findByLoginAndPassword(user.getLogin(), user.getPassword());
}
else {
return Optional.empty();
}
}
private void processMeals(List<MealInfo> meals, Map<Ingredient, Long> shoppingList) {
for (MealInfo mealInfo : meals) {
processIngredientWeights(mealInfo.getMeal().getIngredients(), shoppingList);
}
}
private void processIngredientWeights(List<IngredientWeight> ingredientWeights, Map<Ingredient, Long> shoppingList) {
for (IngredientWeight ingredientWeight: ingredientWeights) {
processIngredientWeight(ingredientWeight, shoppingList);
}
}
private void processIngredientWeight(IngredientWeight ingredientWeight, Map<Ingredient, Long> shoppingList) {
Ingredient ingredient = ingredientWeight.getIngredient();
Long weight = shoppingList.getOrDefault(ingredient, 0L);
weight += ingredientWeight.getWeight();
shoppingList.put(ingredient, weight);
}
编辑:我再次查看了您的代码和域并进行了一些更改,请在此处查看我的示例代码:https ://github.com/akoster/x-converter/blob/master/src/main/java/xcon/stackoverflow/shopping
由于“信息”类,域模型有点混乱。我将它们重命名如下:
MealInfo -> Meal
Meal -> Recipe (with a list of Ingredients)
IngredientInfo -> Ingredient (represents a certain amount of a FoodItem)
Ingredient -> FoodItem (e.g. 'broccoli')
我意识到该服务没有争论!这有点奇怪。如上所示,单独获取用户(例如,取决于当前登录/选择的用户)并将其传递给服务是有意义的。ShoppingListService 现在看起来像这样:
public class ShoppingListService {
private DietMealsService dietMealsService;
public ShoppingListService(DietMealsService dietMealsService) {
this.dietMealsService = dietMealsService;
}
public ShoppingList createShoppingList(User user) {
List<Meal> meals = getMeals(user);
dietMealsService.adjustIngredients(meals);
return createShoppingList(meals);
}
private List<Meal> getMeals(User user) {
Diet diet = user.getDiet();
if (diet == null || diet.getMeals() == null || diet.getMeals().isEmpty()) {
throw new ShoppingServiceException("User doesn't have diet");
}
return diet.getMeals();
}
private ShoppingList createShoppingList(List<Meal> meals) {
ShoppingList shoppingList = new ShoppingList();
for (Meal meal : meals) {
processIngredientWeights(meal.getRecipe().getIngredients(), shoppingList);
}
return shoppingList;
}
private void processIngredientWeights(List<Ingredient> ingredients, ShoppingList shoppingList) {
for (Ingredient ingredient : ingredients) {
shoppingList.addWeight(ingredient);
}
}
}
我还引入了一个“ShoppingList”类,因为传递 Map 是一种代码味道,现在我可以将向购物清单中添加成分的逻辑移动到该类中。
import lombok.Data;
@Data
public class ShoppingList {
private final Map<FoodItem, Long> ingredientWeights = new HashMap<>();
public void addWeight(Ingredient ingredient) {
FoodItem foodItem = ingredient.getFoodItem();
Long weight = ingredientWeights.getOrDefault(foodItem, 0L);
weight += ingredient.getWeight();
ingredientWeights.put(foodItem, weight);
}
}
此服务的单元测试现在如下所示:
@RunWith(MockitoJUnitRunner.class)
public class ShoppingListServiceTest {
@InjectMocks
private ShoppingListService instanceUnderTest;
@Mock
private DietMealsService dietMealsService;
@Mock
private User user;
@Mock
private Diet diet;
@Mock
private Meal meal;
@Test(expected = ShoppingServiceException.class)
public void testCreateShoppingListUserDietNull() {
// SETUP
User user = mock(User.class);
when(user.getDiet()).thenReturn(null);
// CALL
instanceUnderTest.createShoppingList(user);
}
@Test(expected = ShoppingServiceException.class)
public void testCreateShoppingListUserDietMealsNull() {
// SETUP
when(user.getDiet()).thenReturn(diet);
when(diet.getMeals()).thenReturn(null);
// CALL
instanceUnderTest.createShoppingList(user);
}
@Test(expected = ShoppingServiceException.class)
public void testCreateShoppingListUserDietMealsEmpty() {
// SETUP
when(user.getDiet()).thenReturn(diet);
List<Meal> meals = new ArrayList<>();
when(diet.getMeals()).thenReturn(meals);
// CALL
instanceUnderTest.createShoppingList(user);
}
@Test
public void testCreateShoppingListAdjustsIngredients() {
// SETUP
when(user.getDiet()).thenReturn(diet);
List<Meal> meals = Collections.singletonList(meal);
when(diet.getMeals()).thenReturn(meals);
// CALL
instanceUnderTest.createShoppingList(user);
// VERIFY
verify(dietMealsService).adjustIngredients(meals);
}
@Test
public void testCreateShoppingListAddsWeights() {
// SETUP
when(user.getDiet()).thenReturn(diet);
when(diet.getMeals()).thenReturn(Collections.singletonList(meal));
Recipe recipe = mock(Recipe.class);
when(meal.getRecipe()).thenReturn(recipe);
Ingredient ingredient1 = mock(Ingredient.class);
Ingredient ingredient2 = mock(Ingredient.class);
when(recipe.getIngredients()).thenReturn(Arrays.asList(ingredient1, ingredient2));
FoodItem foodItem = mock(FoodItem.class);
when(ingredient1.getFoodItem()).thenReturn(foodItem);
when(ingredient2.getFoodItem()).thenReturn(foodItem);
Long weight1 = 42L;
Long weight2 = 1337L;
when(ingredient1.getWeight()).thenReturn(weight1);
when(ingredient2.getWeight()).thenReturn(weight2);
// CALL
ShoppingList shoppingList = instanceUnderTest.createShoppingList(user);
// VERIFY
Long expectedWeight = weight1 + weight2;
Long actualWeight = shoppingList.getIngredientWeights().get(foodItem);
assertEquals(expectedWeight, actualWeight);
}
}
我希望这是不言自明的。
顺便说一句,单元测试应该只测试被测类。尽量减少对其他类行为的任何假设,并通过模拟它们使其明确,如上所示。出于同样的原因,我总是尽量避免在单元测试中使用“真实”的测试数据,因为它表明这些值对测试很重要——它们并不重要。
推荐阅读
- c# - 声明带参数和不带参数接收的通用委托并将其添加到字典 C#
- excel - 使用 StyleFrame 的 to_excel 方法将多个 python 数据框复制到 excel 中
- django - 跨越关系的查找用户
- c# - 如何处理值在json中有属性?
- mysql - 如果子查询有超过 1 个结果,如何从 select 语句中的子查询返回 1 行?
- vba - 从 accuweather 网站抓取表格数据
- c++ - 如何在 C++ 中导出返回类型为 std::map 的函数
- android - 燃料得到身体对错误的反应
- c# - 在 asp.net 中创建动态控件并保留其状态
- python - 如何通过硒和python找到相对于另一个元素的元素