Test RestController删除Crud方法返回404预期400

时间:2018-05-07 10:17:00

标签: rest testing junit mockito

我的测试方法有问题。我想测试删除方法(shouldNotDeletePersonByGivenId),但测试不起作用。 这是我的测试:

@Test
public void shouldNotDeletePersonByGivenId() throws Exception {
    Mockito.doThrow(new PersonService.NoEntityFoundException()).when(personService).deleteById(1L);

    mockMvc.perform(delete("/persons/{id}", 1))
            .andExpect(status().isBadRequest());
}

在使用中我有这种方法:

public static class NoEntityFoundException extends RuntimeException {
    public NoEntityFoundException() {
        super("There is no Entity in database with given id.");
    }
}

当我开始测试时,我有要求:
java.lang.AssertionError:状态
预计:400
实际:404

在restController中,我的删除方法看起来像这样:

@DeleteMapping("/persons/{id}")
    public ResponseEntity<?> deleteById(@PathVariable Long id) {
        try {
            personService.deleteById(id);
            return ResponseEntity.ok().body("{Deleted}");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cant delete! Entity not exist");
        }
    }

在restController中是我的路径(@PathVariable Long id)

日志:

java.lang.AssertionError: Status 
Expected :400
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:617)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
    at com.softwaremind.crew.people.controller.PersonRestControllerTest.shouldNotDeletePersonByGivenId(PersonRestControllerTest.java:90)
    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)

2018-05-07 12:25:02.218  INFO 11348 --- [       Thread-4] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@6b6776cb: startup date [Mon May 07 12:24:57 CEST 2018]; root of context hierarchy
2018-05-07 12:25:02.223  INFO 11348 --- [       Thread-4] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-05-07 12:25:02.235  WARN 11348 --- [       Thread-4] o.s.b.f.support.DisposableBeanAdapter    : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLException: Baza danych jest już zamknięta (aby zablokować samoczynne zamykanie podczas zamknięcia VM dodaj ";DB_CLOSE_ON_EXIT=FALSE" do URL bazy danych)
Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-197]
2018-05-07 12:25:02.235  INFO 11348 --- [       Thread-4] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2018-05-07 12:25:02.237  INFO 11348 --- [       Thread-4] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

2 个答案:

答案 0 :(得分:0)

从上面我期待/人我的基础路径。对 ?

您是否可以在错误日志中看到正文“无法删除!实体不存在”?

404可能来自错误的道路!

用HttpStatus.BAD_REQUEST .....替换HttpStatus.NOT_FOUND .......... =&gt; 返回ResponseEntity.status(HttpStatus.NOT_FOUND).body(“不能删除!实体不存在”);

答案 1 :(得分:0)

检查你的模拟规则

=&GT; Mockito.doThrow(new PersonService.NoEntityFoundException())。when(personService).deleteById(1L);

在您的代码中,您调用的是函数=&gt; personService.deleteById(ID); =&GT;这引发异常=&gt;你的捕获块捕获它和=&gt; 返回ResponseEntity.status(HttpStatus.NOT_FOUND).body(“不能删除!实体不存在”); =&GT;发送NOT_FOUND状态,即404 !!