java - 带有断言异常的 Spring 单元测试 Java

标签 java spring unit-testing

我正在尝试测试一个 Spring Controller ,该 Controller 具有名为 getProductById 的方法。我有一些我不明白的异常(exception)。我将复制堆栈跟踪。我仍在学习,我不知道是否能让事情顺利。

@Controller
    @RequestMapping("books")
    public class BookController {

        @Autowired
        BookService bookService;
    @RequestMapping("/product")
        public String getProductById(@RequestParam("id") String productId, Model model) {
            model.addAttribute("allBooks", bookService.getBookById(productId));
            return "book";
        }

    }

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext.xml" })
@WebAppConfiguration
@RequestMapping("books")
public class BookControllerTest {

    @Mock
    private BookService bookService;

    @InjectMocks
    private BookController bookController;

    private MockMvc mockMvc;

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(bookController).build();
    }
@Test
    public void testGetProductById() {
        Book book = new Book("3", "book", "book", 5253);
        String id = book.getId();
        assertNotNull("Object can not have null id ", id);

        Book searchedBook = bookService.getBookById(id);
        Assertions.assertThat(searchedBook).isNotNull();

        assertTrue("Found book id should be equal to id being searched", searchedBook.getId().compareTo(id) == 3);
    }

java.lang.AssertionError: expecting actual value not to be null
    at org.fest.assertions.Fail.failure(Fail.java:228)
    at org.fest.assertions.Fail.fail(Fail.java:167)
    at org.fest.assertions.Fail.failIfActualIsNull(Fail.java:100)
    at org.fest.assertions.GenericAssert.isNotNull(GenericAssert.java:238)
    at com.book.controller.test.BookControllerTest.testGetProductById(BookControllerTest.java:61)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    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$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    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:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

最佳答案

 Book searchedBook = bookService.getBookById(id);
 Assertions.assertThat(searchedBook).isNotNull();

您断言您将从图书服务中获得一本书,但事实并非如此,正如您的异常所示:

java.lang.AssertionError: expecting actual value not to be null

显然,searchedBook 为空。原因很简单:为什么不应该这样呢?您的 bookService 是一个 Mock 对象,并且您永远不会告诉该模拟返回任何特定内容,因此它可能始终返回 null

换句话说,你正在做的是这样的:

  1. “嘿,为我创建一个模拟对象 - 一个假装是图书服务的对象”
  2. “嘿,模拟对象,给我 ID 为 X 的书”
  3. 模拟对象:嗯?什么?当你问我这个问题时,你从来没有告诉过我该怎么做。抱歉,我在这里得到的唯一信息是 null。玩得开心。

测试模拟的行为无论如何都是没有意义的。通常你会告诉模拟做一些特定的事情,这样你就可以测试其他的东西。测试一个假装是另一个对象的对象...有什么用?

就您而言,您可能想要测试您的 bookController ,为此您需要模拟 bookservice 以某种方式运行(因为真正的 bookservice可能取决于数据库或类似的东西)。

关于java - 带有断言异常的 Spring 单元测试 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34382889/

相关文章:

java - 如何在viewPager中随机排列内容?

java - 了解 Gradle/Groovy 任务的微妙之处

java - 如何使 Spring @Cacheable 在 AspectJ 切面之上工作?

swift - 如何模拟DataTaskPublisher?

java - 读取JTextfield放入word文件

java - JPanel 字体与打印输出不匹配

java - 基于注释的工厂方法

Java Spring : Compatibility for both transactional and non-transactional versions of mongodb

php - 如何读取/改进 PHP 计算的 C.R.A.P 指数

java - SOAPUI 转移属性(property)