对springboot得service层方法进行测试,由于我的启动类与java代码不在一个模块里,启动类在web模块,service在普通模块内,测试得时候遇到了一些问题。如下图所示。
下图,测试类的路径与启动类的路径要一致,切记,切记
启动类代码
package com.springboot.controller;
import org.mybatis.spring.annotation.MapperScan;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@MapperScan(basePackages = "com.springboot.*.mapper")
@ComponentScan(basePackages={"com.springboot"})
public class Application {
public static void main(String args[]){
System.out.println("垃圾springboot");
SpringApplication.run(Application.class, args);
}
}
service层
@Service
public class IMybatisUserServiceImpl implements IMybatisUserService {
@Autowired
public MyBatisDao myBatisDao;
@Override
public List<MybatisUser> selectAll() {
List<MybatisUser> mybatisUsers = myBatisDao.pageByFilterRows();
return mybatisUsers;
}
}
dao层
import com.springboot.mybatistest.entity.MybatisUser;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface MyBatisDao {
public List<MybatisUser> pageByFilterRows();
}
测试类
package com.springboot.controller;
import com.springboot.mybatistest.entity.MybatisUser;
import com.springboot.mybatistest.service.IMybatisUserService;
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;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class Test1 {
@Autowired
public IMybatisUserService mybatisUserService;
@Test
public void test(){
mybatisUserService.select();
List<MybatisUser> mybatisUsers = mybatisUserService.selectAll();
System.out.println(mybatisUsers.size());
}
}
注:所有的方法都写完后,启动测试类,报错,说找不到mapper文件中的pageByFilterRows方法。最后在sb-core模块的pom文件中添加以下配置。因为如果不添加一下配置,程序只会默认去找resources下的配置文件,所以找不到我们自己写的mapper文件。添加以下配置后,解决问题
<build>
<resources>
<!--将java代码目录中的xml输出,默认不输出除resources目录外的xml文件-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>