测试休息控制器时断言错误预期:200实际:404

时间:2019-01-08 21:55:31

标签: java spring-boot testing mockito

我正在尝试测试我的简单rest控制器方法以获取所有报价,但我始终会得到java.lang.AssertionError:期望状态:200实际:404。我不知道模拟或查找我的组件是否有问题。我试图在其他帖子中找到解决方案,但没有一个与我的问题匹配。有什么想法吗?

我的服务:

@Service
@Transactional
class OfferServiceImpl implements OfferService {

private OfferRepository offerRepository;

@Autowired
public OfferServiceImpl(OfferRepository offerRepository) {
    this.offerRepository = offerRepository;
}

@Override
public List<Offer> getAll(){
    return (List<Offer>) offerRepository.findAll();
}

我的控制器:

@RestController
@RequestMapping("/api/offers")
class OfferRestController {

private OfferService offerService;

@Autowired
public OfferRestController(OfferService offerService) {
    this.offerService = offerService;
}

@GetMapping
List<Offer> getAllOffers(){
    return offerService.getAll();
}

我的测试班:

@RunWith(SpringRunner.class)
@WebMvcTest(value = OfferRestController.class)
public class OfferControllerIntegrationTest {

private Offer offer1;
private Offer offer2;

@MockBean
private OfferService offerServiceMock;

@Autowired
private WebApplicationContext webApplicationContext;

@Autowired
private MockMvc mvc;

@Before
public void setUpOffers(){
    offer1 = new Offer("Java Dev",
            4000,
            5000,
            "CEO",
            "Java",
            "Lorem ipsum",
            "user@gmail.com",
            true);
    offer2 = new Offer("PHP Dev",
            4000,
            5000,
            "CEO",
            "PHP",
            "Lorem ipsum",
            "user@gmail.com",
            true);
}

@Before
public void setUp() {
    this.mvc = standaloneSetup(new OfferRestController(offerServiceMock))
            .alwaysExpect(MockMvcResultMatchers.content()
                    .contentType("application/json;charset=UTF-8"))
            .defaultRequest(get("/").accept(MediaType.APPLICATION_JSON))
            .alwaysExpect(status().isOk())
            .build();
    this.mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
            .alwaysDo(print())
            .build();
}


@Test
public void givenOffers_whenGetOffers_thenReturnJsonArray() throws Exception{

    List<Offer> allOffers= Arrays.asList(offer1,offer2);

    given(offerServiceMock.getAll()).willReturn(allOffers);

    mvc.perform(get("/api/offers")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$",hasSize(2)))
            .andExpect(jsonPath("$[0].name").value(offer1.getName()))
            .andExpect(jsonPath("$[1].name").value(offer2.getName()))
            .andDo(print());

    verify(offerServiceMock,times(1)).getAll();
    verifyNoMoreInteractions(offerServiceMock);

}
}

我的应用程序:

@SpringBootApplication
@EntityScan(basePackageClasses = {App.class, Jsr310JpaConverters.class})
@ComponentScan({"com"})
public class App {
public static void main(String[] args) {
    SpringApplication.run(App.class, args);
} 
}

我的问题:

 MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /api/offers
   Parameters = {}
      Headers = {Content-Type=[application/json]}
         Body = <no character encoding set>
 Session Attrs = {}

 Handler:
         Type = 
 org.springframework.web.servlet.resource.ResourceHttpRequestHandler

 Async:
 Async started = false
 Async result = null

Resolved Exception:
         Type = null

ModelAndView:
    View name = null
         View = null
        Model = null

FlashMap:
   Attributes = null

MockHttpServletResponse:
       Status = 404
Error message = null
      Headers = {}
 Content type = null
         Body = 
Forwarded URL = null
Redirected URL = null
      Cookies = []

java.lang.AssertionError: Status 
Expected :200
Actual   :404
<Click to see difference>


at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at brozek.com.offer.OfferControllerIntegrationTest.givenOffers_whenGetOffers_thenReturnJsonArray(OfferControllerIntegrationTest.java:89)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

1 个答案:

答案 0 :(得分:0)

通常,集成测试设置应使用@WebMvcTest(value = OfferRestController.class)模拟在测试Spring上下文中创建的控制器。常用语法是:

@RunWith(SpringRunner.class)
@WebMvcTest(value = OfferRestController.class)
@AutoConfigureMockMvc
public class OfferRestControllerTest {

  @MockBean
  private OfferService offerService;

  @Autowired
  private MockMvc mvc;

}

在您的测试中,对没有正文的GET请求设置Content-Type毫无意义,

.contentType(MediaType.APPLICATION_JSON)

从Spring 4.1开始,没有必要在单个构造函数上使用@Autowired。您可以通过在此处删除@Autowired来简化代码:

public OfferServiceImpl(OfferRepository offerRepository) {
  this.offerRepository = offerRepository;
}