Java 预期状态:<200> 但在春季测试中为:<404>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19138255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Status expected:<200> but was:<404> in spring test
提问by gstackoverflow
I have this class:
我有这门课:
package controllers;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashSet;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.ui.Model;
import org.springframework.web.context.WebApplicationContext;
import com.epam.hhsystem.model.candidate.Candidate;
import com.epam.hhsystem.services.CandidateService;
import com.epam.hhsystem.web.controllers.CandidateMenuController;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.context.junit4.*;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.request.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class CandidateControllerTest {
@Mock(name = "candidateService")
private CandidateService candidateService;
@InjectMocks
private CandidateMenuController candidateMenuController = new CandidateMenuController();
@Autowired
WebApplicationContext wac;
MockMvc mockMvc;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}
@Test
public void testgoToCandidateMenuMockMvc() throws Exception {
//MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/goToCandidateMenu");
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/goToCandidateMenu");
ResultActions result = mockMvc.perform(request);
result.andExpect(status().isOk());
}
}
When I execute it I see:
当我执行它时,我看到:
java.lang.AssertionError: Status expected:<200> but was:<404>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers.match(StatusResultMatchers.java:549)
at org.springframework.test.web.servlet.MockMvc.andExpect(MockMvc.java:141)
at controllers.CandidateControllerTest.testgoToCandidateMenuMockMvc(CandidateControllerTest.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access@Controller
public class CandidateMenuController extends AbstractController {
...
@RequestMapping("/goToCandidateMenu")
public String goToCandidateMenu() {
return "candidateMenu";
}
...
}
0(ParentRunner.java:42)
at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Controller code:
控制器代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Включаем опцию использования конфигурационных аннотаций (@Annotation-based configuration)-->
<context:annotation-config />
<context:component-scan base-package="com.epam.hhsystem.jpa" />
<context:component-scan base-package="com.epam.hhsystem.services" />
<!-- Файл с настройками ресурсов для работы с данными (Data Access Resources) -->
<import resource="data.xml" />
</beans>
Can you help me to fix my problem?
你能帮我解决我的问题吗?
UPDATE
更新
BeanConfig.xml:
BeanConfig.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Настраивает управление транзакциями с помощью аннотации @Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Менеджер транзакций -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Непосредственно бин dataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
p:url="jdbc:sqlserver://10.16.9.52:1433;databaseName=hhsystemTest;"
p:username="userNew"
p:password="Pass12345" />
<!-- Настройки фабрики сессий Хибернейта -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:test/hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">create-drop</prop> -->
</props>
</property>
</bean>
</beans>
data.xml
数据文件
@Before
public void before() {
MockitoAnnotations.initMocks(this);
MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}
回答by M. Deinum
Your test setup is wrong you aren't initializing the MockMvc
correctly and that is al clearly in the reference guide. FIrst of all you have twice the initializing code and you aren't assing the result of the call to the build
method. So you are basically left with an empty MockMvc
object.
您的测试设置是错误的,您没有MockMvc
正确初始化,这在参考指南中很清楚。首先,您有两倍的初始化代码,并且您没有评估对该build
方法的调用结果。所以你基本上只剩下一个空MockMvc
对象。
@Before
public void before() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}
Should be
应该
<mvc:annotation-driven></mvc:annotation-driven>
As stated this is all explained in the reference guide.
如前所述,这在参考指南中都有解释。
回答by Sotirios Delimanolis
I believe you just haven't enabled <mvc:annotation-driven>
in your beanconfig.xml
and so your @Controller
classes just aren't being registered.
我相信你只是还没有启用<mvc:annotation-driven>
在你beanconfig.xml
和让你的@Controller
类只是没有被注册。
Add this
添加这个
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class)
@WebAppConfiguration
public class ResourceTest {
...
@Configuration
@EnableWebMvc
@ComponentScan( basePackages = { "..." } )
static class ContextConfiguration {
}
}
回答by Schiman
I added this annotations to configuration class and work it:
我将此注释添加到配置类并对其进行处理:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class SimpleTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() throws Exception {
mockMvc = webAppContextSetup(webApplicationContext)
.build();
}
@Test
public void test() throws Exception {
mockMvc.perform(get("/simple")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().is(200));
}
}
回答by Enrico Giurin
This is my working solution. Hope it helps.
这是我的工作解决方案。希望能帮助到你。
@WebMvcTest(UserStatsController.class)
public class UserStatsControllerTest {
..
}
回答by Madhan Ganesh
In my case, I was missing the below annotation and was getting this error.
就我而言,我缺少以下注释并收到此错误。
##代码##Note that the class of the controller and NOT the test. Make sure as well if you load other class using @ContextConfiguration(NOT the test) not load test class.
请注意,控制器的类而不是 test。如果您使用 @ContextConfiguration( NOT the test)加载其他类,请确保不加载测试类。
回答by cjn
In the case that you make a really stupid "going to fast for your own good" typo like I did, make sure that your controller test class does NOT have the same name as the controller class itself. Most people know this, but you can get into this same error condition the names are identical, and it may not my immediately obvious why. To clarify further, make sure you DO NOT DO THIS:
如果您像我一样犯了一个非常愚蠢的“为了自己好而禁食”的错字,请确保您的控制器测试类与控制器类本身不具有相同的名称。大多数人都知道这一点,但是您可能会遇到相同的错误条件,名称相同,并且可能不是我立即显而易见的原因。为了进一步澄清,请确保您不要这样做:
Controller name: MyController
Test class name: MyController
控制器名称:MyController
测试类名称:MyController
This can cause your MockMvc tests to fail with status 404... which is not very obvious.
Naming [obviously] should be more like:
这可能会导致您的 MockMvc 测试失败并显示状态 404... 这不是很明显。
命名 [显然] 应该更像是:
Controller name: MyController
Test class name: MyControllerTest
控制器名称:MyController
测试类名称:MyControllerTest
回答by Yupei Xiong
My problem was I did not have @ComponentScan() it was pretty embarrassing. It was also hard to find.I,myself overlooked my SpringBootApplication.
我的问题是我没有 @ComponentScan() 这很尴尬。它也很难找到。我自己忽略了我的 SpringBootApplication。