欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

后端Mock测试,屏蔽spring/数据库

程序员文章站 2022-06-28 23:05:03
springboot环境中,对service层进行单元测试,使用mockito模拟service中mapper的调用方法,屏蔽数据库调用,不启动spring实体类@Dataclass Person { private String name; public Person(String name) { this.name = name; }}逻辑层实现类@Serviceclass PersonServiceImpl implements PersonS...

springboot环境中,对service层进行单元测试,使用mockito模拟service中mapper的调用方法,屏蔽数据库调用,不启动spring

实体类

@Data
class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }
}

逻辑层实现类

@Service
class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonMapper personMapper;

    public Person getById(Serializable id) {
        return personMapper.getById(id);
    }
}

测试类

@RunWith(SpringRunner.class)
public class MockDemoTest {

    PersonService personService = new PersonServiceImpl();

    @Test
    public void runTest() {
        PersonMapper personMapper = (PersonMapper) init(PersonService, PersonMapper.class);
        Mockito.doReturn(new Person("mike")).when(personMapper).getById(any());

        Person testPerson = personService.getById("testId");
        Assert.isTrue(testPerson.getName().equals("mike"), "");
    }

    Object init(Object mainClass, Class memberField) throws Exception {
        Class<?> clazzRoot = mainClass.getClass();
        Object obj = Mockito.mock(memberField);
        Field field = clazzRoot.getDeclaredField(StrUtils.headToLowerCase(memberField.getSimpleName()));
        field.setAccessible(true);
        field.set(mainClass, obj);
        return obj;
    }
}

相当于使用Mockito模拟了逻辑层内部成员变量,然后通过set方法将模拟出的对象赋值给逻辑层的成员变量。

如果是需要启动spring环境的测试,可以使用@MockBean注解,测试类改为

@RunWith(SpringRunner.class)
public class MockDemoTest {

    PersonService personService = new PersonServiceImpl();
	@MockBean
	PersonMapper personMapper;
    @Test
    public void runTest() {
        PersonMapper personMapper = (PersonMapper) init(PersonService, PersonMapper.class);
        Mockito.doReturn(new Person("mike")).when(personMapper ).getById(any());

        Person testPerson = personService.getById("testId");
        Assert.isTrue(testPerson.getName().equals("mike"), "");
    }

}

本文地址:https://blog.csdn.net/huanshen7428/article/details/111996401

相关标签: java 单元测试