错误:在为Spring Controller执行@WebMvcTest时无法找到@SpringBootConfiguration

Mee*_*ary 34 java spring-mvc spring-test spring-boot

我正在测试下面给出的控制器

@Controller
public class MasterController {

@GetMapping("/")
public String goLoginPage(){
    return "index";
}
}
Run Code Online (Sandbox Code Playgroud)

我下面这个春天文件来测试我的控制器.现在,我想通过实例化Web层而不是文档中给出的整个Spring上下文来测试我的控制器.下面是我的相同代码.

@RunWith(SpringRunner.class)
@WebMvcTest
public class MasterControllerTestWithWebLayer {

@Autowired
MockMvc mockMvc;

@Autowired
MasterController masterController;


@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test
public void testLoginHome() throws Exception{
    mockMvc.perform(get("/"))
    .andExpect(status().isOk())
    .andExpect(view().name("index"));
}

}
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,我收到错误Unable to find @SpringBootConfiguration,...etc.但我很困惑为什么当我们不希望它实例化它但只想使用Web层时它要求Spring配置.请指出正确的方向,这里发生了什么.以及如何解决这个问题.谢谢

Mee*_*ary 82

所以这是解决方案:

有关检测测试配置文档说:

搜索算法从包含测试的包开始工作,直到找到@SpringBootApplication或@SpringBootConfiguration注释类.只要您以合理的方式构建代码,通常就会找到主要配置.

因此,@SpringBootApplication类包层次结构中的类应该高于测试类,例如,如果测试类在包中,com.zerosolutions.controller那么@SpringBootApplication类应该在比com.zerosolutions.controller包更高的包中,即com.zerosolutions或者 com.

问题

但是如果@SpringBootApplication类与测试类处于同一级别,它将无法找到它,即com.zerosolutions.general.在这种情况下,您将收到以下错误:

java.lang.IllegalStateException:无法找到@SpringBootConfiguration,您需要在测试中使用@ContextConfiguration或@SpringBootTest(classes = ...)

如果您正在运行集成测试,则可以明确提及@SpringBootApplication此类

@RunWith(SpringRunner.class)
@SpringBootTest(classes={SpringBootApp.class})
Run Code Online (Sandbox Code Playgroud)

但是如果你想对控制器进行单元测试,则不需要启动整个Spring上下文.您可以替换,而@SpringBootTest@WebMvcTest(MasterController.class).这将仅实例化Web层,MasterController而不是整个Spring上下文.

问题

但问题是你将再次遇到我们之前遇到的错误:

java.lang.IllegalStateException:无法找到@SpringBootConfiguration,您需要在测试中使用@ContextConfiguration或@SpringBootTest(classes = ...)

并且@WebMvtTest没有明确提及类的classes属性.所以有两个解决方案.@SpringBootTest@SpringBootApplication

第一步:将您的应用程序类移动到高于测试类ie com.zerosolutionscom包的包.

第二:@SpringBootApplication明确提到你的课程,如下所示

@RunWith(SpringRunner.class)
@WebMvcTest(MasterController.class)
@ContextConfiguration(classes={SpringBootApp.class})
Run Code Online (Sandbox Code Playgroud)

希望能够清除Spring Test Configuration的混乱.谢谢


Tad*_*egn 23

如果您的Application.java类(在src/main/java中)位于

com.A.B

你的测试类ApplicationTest.java(在src/test/java中)需要在

com.A.Bcom.A.B.Ccom.A.B.C.D

如果测试类位于以下包中,则会出现此错误

com.Acom.A.Ccom.A.D

在春季靴子中,一般规则是测试类包装名称需要开始使用待测试的JAVA类包装的包装名称