首页 > 解决方案 > 使用 Mock 和 InvocationOnMock 进行单元测试

问题描述

我是 Java Spring 的新手,我需要 Mockito 的指导。

我试图测试我的服务层,但它一直无法验证模拟用户名和电子邮件地址。

我目前真的很困惑我应该如何正确地做到这一点。

谢谢!

用户服务.java

package com.example.newproject.newproject.service;

import com.example.newproject.newproject.entity.User;

import java.util.List;

public interface UserService {
    boolean addUser(String username,String email);
    List<User> viewAllUsers();
}

UserServiceImpl.java

package com.example.newproject.newproject.service.impl;

import com.example.newproject.newproject.entity.User;
import com.example.newproject.newproject.repository.UserRepository;
import com.example.newproject.newproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;


    @Override
    public boolean addUser(String username, String email) {
        if(userRepository.findByUsernameAndEmail(username, email) == null)
        {
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            userRepository.save(user);
            return false;

        }else{
            return true;
        }

    }

    @Override
    public List<User> viewAllUsers() {
        return userRepository.findAll();
    }
}

我的模拟

@Test
public void testAddUser(){
    Mockito.when(userRepository.findByUsernameAndEmail("Google","google@google.com")).then(invocationOnMock ->  {

        User user = new User();
        return user;
    });

    boolean result =  userService.addUser("Google","google@google.com");
    Assert.assertFalse(result);

    Mockito.verify(userRepository, Mockito.times(1)).save(userArgumentCaptor.capture());
    User user = userArgumentCaptor.getValue();
    Assert.assertEquals("Google", user.getUsername());
    Assert.assertEquals("google@google.com", user.getEmail());
}

我得到的错误是

  java.lang.AssertionError

在运行期间

标签: javaspring-boot

解决方案


推荐阅读