首先,框架中要引入测试包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

1.测试类添加注解@RunWith(SpringRunner.class)、@SpringBootTest,测试方法添加注解@Test

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootTestJunitTest {
    @Test
    public void test() {
        System.out.print("test");
    }
}

 2.测试方法中使用@Autowired注解调用mapper

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootTestJunitTest {
    @Autowired
    private TestMapper testMapper;

    @Test
    public void test() {
        System.out.print("test");
        testMapper.test();
    }
}

直接在serviceImpl中测试已经写好的方法

@RunWith(SpringRunner.class)
@SpringBootTest
@Service("springBootTestJunitTestService")
public class SpringBootTestJunitTestImpl implements SpringBootTestJunitTestService {
    @Autowired
    private TestMapper testMapper;

    @Test
    public void test() {
        //直接使用this调用本类中方法
        String userName = this.getUserName(3);
        System.out.print(userName);
        //不能通过创建类对象的方式调用,否则会出现testMapper对象为null问题
        // SpringBootTestJunitTestImpl testImplObj = new SpringBootTestJunitTestImpl();
        // String userName = testImplObj.getUserName(3);
    }
    
    @Override
    public String getUserName(Integer userId){
        User user = testMapper.getUserName(userId);
        String userName = user.getUserName();
        return userName;
    }

}

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐