springboot 单元测试service遇到的坑(cannot resolve symbol “RunWith” )

springboot项目,对service层进行单元测试的步骤:

1.添加相关依赖,

2.在测试类添加两个注解:@RunWith(SpringJUnit4ClassRunner.class),

                                        @SpringBootTest(classes = ChargerOperateApplication.class),

                                        添加@Before\@After,注入自己的bean

3.编写测试代码。

具体如下:

1.添加相关依赖,

 


        
            junit
            junit
        
        
            org.springframework.boot
            spring-boot-test
        
        
            org.springframework
            spring-test
            4.3.3.RELEASE
        
        
            org.hibernate
            hibernate-validator
            5.3.3.Final
        
        
            org.mockito
            mockito-all
            1.9.5
            test
        

注意:junit最好使用4.5以上的版本,否则有可能报错,或者报cannot resolve symbol runwith。

2.代码编写:
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.junit.runner.RunWith;
/**
 * Created by arvin on 2018/5/16.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ChargerOperateApplication.class)
public class TestJunit {


    @Autowired
    private NetecoAlarmDataService netecoAlarmDataService;


    @Test
    public void test1() throws Exception {
        String url = "";
        NetecoAlarmData netecoAlarmData = new NetecoAlarmData();
        netecoAlarmData.setAlarmId(4);
        netecoAlarmData.setAlarmName("123");
        netecoAlarmData.setAlarmSerialNo(201805166);
        netecoAlarmData.setGlobalSN(6);
        netecoAlarmData.setCleared(false);
        netecoAlarmData.setClearedTime("2018-05-16 01:10:10");
        netecoAlarmData.setAlarmTime("2018-05-16 01:10:10");
        netecoAlarmData.setDeviceId("2343");
        netecoAlarmData.setLocationInfo("nanjing-jiangning");
        netecoAlarmData.setThresholdInfo("fdsfds");
        netecoAlarmDataService.addNetecoAlarmData(url,"",netecoAlarmData);
    }

}

3.异常出现和解决:

异常:代码写好发现导包失败,并且报cannot resolve symbol runwith。

解决思路:

1.jar包是否有冲突,如若有,先解决jar包冲突,

2.junit的版本,最好使用4.5以上版本,我用的4.12版本


junit
junit
4.12
test

3.重新加载jar包:maven-----reimport all

散步走完后还是报错!!!!!!!!!

最后直接复制了runwith的包名放进代码:import org.junit.runner.RunWith;

参考博客:https://blog.csdn.net/bobo_12138/article/details/77609109

 

你可能感兴趣的:(单元测试,springboot,springboot,service单元测试)