java.lang.AssertionError: Status Expected :200 Actual :404

Springboot 2.x 搭建项目 mock 测试 404 问题
在练习 Springboot 2.x 搭建项目做 mock 测试时出现 404 错误,网上资料少且现有解决方法未解决。作者发现是因 @RequestMapping 和测试代码中地址未写“/”导致,建议统一写法以避免该问题。

练习Springboot2.x搭建项目的时候做mock测试报出如下错误:

java.lang.AssertionError: Status 
Expected :200
Actual   :404

网上资料不多,查找了几个解决方法并没有解决问题
简书上有一个是这样写的:
在这里插入图片描述
参考:简书:糖先生要健康生活的文章:spring boot mock mvc 404错误原因
我的错误是另外一个原因:
Controller代码:

@RestController
public class UserController {
    @RequestMapping("hello")
    public String hello(){
        return "hello world2";
    }
}

Test代码:

import org.junit.Before;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * @Author: lt
 * @Date: 2019/7/10 15:31
 */
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
  @Autowired
  private WebApplicationContext wac;


  private MockMvc mockMvc;

  @Before
  public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }

  @Test
  public void hello() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("hello").accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();
  }
}

因为习惯问题,@RequestMapping(“hello”)的地址会不写“/”,在测试 mockMvc.perform(MockMvcRequestBuilders.get(“hello”).accept(MediaType.APPLICATION_JSON))也没有写“/”
就是这个“/”导致了404

正确写法:

mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))

为了统一,建议@RequestMapping(“hello”)也写成:

@RequestMapping("/hello")
void testBuyOrderProcess(JobParameters parameters) throws Exception { mockCurrencyEntity("USD", "JP_GROUP1"); mockBusinessDateEntity(11); mockFixedRateList(2); when(exchangeOrderManageRepository.multiGetBatchTargets(any())).thenReturn(createBuyOrderTargets()); when(exchangeBusinessDateRepository.update(any())).thenReturn(1); when(depositWithdrawalLogic.doRepaymentForEc(any(), any())).thenReturn(true); when(depositWithdrawalLogic.doReceipt(any(), any(), anyInt(), anyString(), any())).thenReturn(true); var execution = jobLauncherTestUtils.launchStep(STEP_NAME, parameters); assertThat(execution.getExitStatus()).isEqualTo(ExitStatus.COMPLETED); ArgumentCaptor<MultiGetBatchTargetEntity> multiGetBatchTargetEntityArgumentCaptor = ArgumentCaptor.forClass( MultiGetBatchTargetEntity.class); ArgumentCaptor<Account> accountArgumentCaptor = ArgumentCaptor.forClass(Account.class); verify(depositWithdrawalLogic).doRepaymentForEc(multiGetBatchTargetEntityArgumentCaptor.capture(), accountArgumentCaptor.capture()); assertThat(multiGetBatchTargetEntityArgumentCaptor.getValue()).usingRecursiveComparison() .ignoringCollectionOrder().isEqualTo(createBuyOrderTargets().getFirst().toString()); assertThat(accountArgumentCaptor.getValue()).usingRecursiveComparison() .ignoringCollectionOrder().isEqualTo( createAccount(createBatchTargets().getFirst())); verify(depositWithdrawalLogic).doReceipt(any(), any(), any(), any(), any()); } 报出一下错误 Expecting actual: com.sbibits.evanes.exchange.batch.entity.MultiGetBatchTargetEntity@4d73d3d1 to be equal to: "com.sbibits.evanes.exchange.batch.entity.MultiGetBatchTargetEntity@28d728f1" when recursively comparing field by field, but found the following difference: Top level actual and expected objects differ: - actual value : com.sbibits.evanes.exchange.batch.entity.MultiGetBatchTargetEntity@4d73d3d1 - expected value: "com.sbibits.evanes.exchange.batch.entity.MultiGetBatchTargetEntity@28d728f1" Compared objects have java types and were thus compared with equals method The recursive comparison was performed with this configuration: - no equals methods were used in the comparison EXCEPT for java JDK types since introspecting JDK types is forbidden in java 17+ (use withEqualsForType to register a specific way to compare a JDK type if you need it) - collection order was ignored in all fields in the comparison - these types were compared with the following comparators: - java.lang.Double -> DoubleComparator[precision=1.0E-15] - java.lang.Float -> FloatComparator[precision=1.0E-6] - java.nio.file.Path -> lexicographic comparator (Path natural order) - actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call strictTypeChecking(true) to change that behavior). - the introspection strategy used was: DefaultRecursiveComparisonIntrospectionStrategy java.lang.AssertionError: Expecting actual: com.sbibits.evanes.exchange.batch.entity.MultiGetBatchTargetEntity@4d73d3d1 to be equal to: "com.sbibits.evanes.exchange.batch.entity.MultiGetBatchTargetEntity@28d728f1" when recursively comparing field by field, but found the following difference: Top level actual and expected objects differ: - actual value : com.sbibits.evanes.exchange.batch.entity.MultiGetBatchTargetEntity@4d73d3d1 - expected value: "com.sbibits.evanes.exchange.batch.entity.MultiGetBatchTargetEntity@28d728f1" Compared objects have java types and were thus compared with equals method The recursive comparison was performed with this configuration: - no equals methods were used in the comparison EXCEPT for java JDK types since introspecting JDK types is forbidden in java 17+ (use withEqualsForType to register a specific way to compare a JDK type if you need it) - collection order was ignored in all fields in the comparison - these types were compared with the following comparators: - java.lang.Double -> DoubleComparator[precision=1.0E-15] - java.lang.Float -> FloatComparator[precision=1.0E-6] - java.nio.file.Path -> lexicographic comparator (Path natural order) - actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call strictTypeChecking(true) to change that behavior). - the introspection strategy used was: DefaultRecursiveComparisonIntrospectionStrategy at com.sbibits.evanes.exchange.batch.job.b03003.B03003BatchTest.testBuyOrderProcess(B03003BatchTest.java:221) at java.base/java.lang.reflect.Method.invoke(Method.java:580) at java.base/java.util.Optional.ifPresent(Optional.java:178) at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) 怎么修改
最新发布
11-04
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值