junit单元测试Mock

        在平常工作,经常会用到单元测试,那么单元测试应该怎么写呢?

        1:引入包:

        
            junit
            junit
            4.12
            test
        
        
            org.mockito
            mockito-all
            2.0.2-beta
            test
        
        
            org.powermock
            powermock-api-mockito2
            2.0.9
            test
        
        
            org.powermock
            powermock-module-junit4
            2.0.0
            test
        

        2:service:

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    public StuentVO queryById(Long id) {
        return studentDao.queryById(id);
    }
}

        3:单元测试:

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import test.boot.SpringbootApplicationTest;
import test.boot.service.StudentService;
import test.boot.vo.StuentVO;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootApplicationTest.class)
public class StudentTest {

    @Mock
    private StudentService studentService;

    @Test
    public void test01(){
        StuentVO vo = new StuentVO();
        vo.setName("大杜");
        vo.setPhone("12345678911");
        vo.setId(1L);
        PowerMockito.when(studentService.queryById(1L)).thenReturn(vo);
        StuentVO queryVO = studentService.queryById(1L);
        Assert.assertEquals("姓名不一致", vo.getName(), queryVO.getName());
    }
}

        4:运行结果:

junit单元测试Mock_第1张图片

        5:使用Mock,比如有些数据依赖数据库查询,如果数据库数据更改,可能会使单元测试报错;或者方法依赖于其他系统的接口等,如果需要完成单元测试,那么mock一个对应的类以及应该返回的值。

        风景很美,生活,一直在路上!2024,新的一年,加油!

你可能感兴趣的:(单元测试,Java,junit,单元测试,log4j)