SpringBoot integrates Junit test

SpringBoot integrates Junit test

It is assumed that mybatis and web have been configured and integrated. The integration of test methods is carried out directly below.

1. SpringBoot introduces springboot test dependencies
        <!--整合springboot与junit测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

2. Generate test methods
Before generating the test method, it has been assumed that all service interfaces and implementations have been completed.

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {
    
    

    //假设调用了mybatis提供的mapper接口。
    
    @Override
    public int addUser(String str) {
    
    
        System.out.println("假设这是一个业务逻辑,并且调用了mybatis的sql语句:" + str);
        return 1;
    }
}

Place the cursor on the name of the class, press the shortcut key Ctrl+Shift+T to create a test class, and the generated test class is in the test folder.

UserServiceImplTest.java

/**
 * 类上面的两个注解不能缺少
 *@RunWith(SpringRunner.class)
 *@SpringBootTest
 *测试方法的注解不能缺少
 *@Test
 *直接注入UserService对象就能够实现测试接口的调用,否则是不能用的。
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {
    
    

    @Autowired
    private UserService userService;

    @Test
    public void addUser() {
    
    
        String str = "嘿嘿";
        int i = userService.addUser(str);
        System.out.println("返回结果:" + i);
    }
}

3. Test results
insert image description here

Guess you like

Origin blog.csdn.net/weixin_52859229/article/details/129615915