Service層的怎麼寫測試類

不忘初心2021發表於2024-04-12

給出具體程式碼

程式碼部分

package com.java.service;

/**
 * @Description:
 * @Author: qiuxie
 * @Create: 2024/4/12 0:26
 */
public interface TestService {

    void test();
}


package com.java.service;

import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author: qiuxie
 * @Create: 2024/4/12 0:26
 */
@Service
public class TestServiceImpl implements TestService{
    @Override
    public void test() {
        System.out.println("service測試.....");
    }
}

  啟動類

package com.java;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Description:  設定年輕代和老年代的比例  1:4
 * E:S0:S1  8:1:1
 * @Author: Yourheart
 * @Create: 2023/4/21 11:27
 */
@SpringBootApplication()
public class MysqlServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(MysqlServiceApplication.class, args);
    }

}

  無任何配置檔案

測試類程式碼

package com.java;

import com.java.service.TestService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @Description:
 * @Author: qiuxie
 * @Create: 2024/4/12 0:27
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Tests {

    /**
     * 這裡做物件的宣告
     */
    @Autowired
    private TestService testService;

    @Test
    public void test(){
        testService.test();
    }

}

  最後給出pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>service-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.14</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <java.version>1.8</java.version>
        <skipTests>true</skipTests>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


</project>

  

相關文章