Sprintboot的一个测试用例

本文详细解析了Spring Boot测试中出现的java.lang.IllegalStateException异常原因,即测试代码与源代码包路径不一致导致的问题,并提供了修改包路径以解决该问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近做测试代码,编译总是不通过报出下面的错误

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
    at org.springframework.util.Assert.state(Assert.java:70)
    at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:202)

查了一下百度后来发现是测试代码与源代码 的package 不一样导致。
后来将他们的包名改为一样的就可以了
例如:

test
--package com.xxx.yyy.controller;
src
--package com.xxx.yyy.controller;

测试代码如下

package com.xxx.yyy.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSON;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TestXXXController {
	@Autowired
	private WebApplicationContext wac;

	private MockMvc mvc;
	private MockHttpSession session;
	
	@LocalServerPort
	private int port;
	
	private String host = "http://localhost:";
	
	private String path = "xxx";
	
	@Autowired
	private TestRestTemplate restTemplate;

	@Test
	public void testList() throws UnsupportedEncodingException{
		Map<String, Object> param =new HashMap<String, Object>();
		param.put("id", 19);
		param.put("menuId", "1");
		StringBuffer sb = getParameterString(param);
		
		String json = this.restTemplate.getForObject("http://localhost:" + port + "/xxx/ccc/list.json?"+sb.toString(),
				String.class);
		System.out.println(json);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值