JUnit与Mockito测试方法输出:when()与Assert.equals()使用场景解惑
Mockito.when() vs Assert.equals() Let's start by clarifying that these two tools serve completely different purposes in unit testing—they're not alternatives, but complementary parts of a typical test workflow.
When to Use Mockito.when()
Mockito.when() is all about setting up mock behavior before you run your test code. Mockito uses this method to define what a mocked object should do when one of its methods is called.
You'll want to use it in these scenarios:
- Your test class depends on an external component (like a database DAO, a third-party API client, or another service) that you don't want to invoke directly. For example, if you're testing a service that fetches articles, you'd mock the ArticleDAO and use
when(mockArticleDAO.getArticles()).thenReturn(testArticles)to return a predefined list instead of hitting a real database. - You need to test edge cases or error handling. For instance, you can use
when(mockService.fetchData()).thenThrow(new IOException())to simulate a failed API call and verify that your code handles the exception correctly. - You want to isolate the code you're testing. By mocking dependencies, you ensure that your test only fails because of issues in the class under test, not because of problems in external services.
Note on Your Error
The MissingMethodInvocationException you hit happens when you try to use when() on something that's not a Mockito-created mock. Double-check that the object you're calling when() on was created with Mockito.mock(YourClass.class) or annotated with @Mock (and that you've initialized Mockito properly, like with @ExtendWith(MockitoExtension.class) in JUnit 5).
When to Use Assert.equals() (usually assertEquals() in JUnit)
Assert.equals() (more commonly used as assertEquals(expected, actual) in testing frameworks like JUnit) is for verifying results after running your test code. It checks that the actual output or state of your code matches what you expected.
Use it when:
- You want to confirm that a method returns the correct value. For example, after calling
articleService.processArticles(testArticles), you'd useassertEquals(expectedProcessedCount, actualProcessedCount)to check if the count is right. - You need to validate that an object's state has changed correctly. Like, after updating a user's profile, you'd assert that the user's email attribute matches the new value you set.
- You're testing calculations, transformations, or any logic where you can define a clear expected outcome.
Quick Summary
Think of it as a two-step process:
- Set up mock behavior with
Mockito.when()to control how dependencies behave during the test. - Run your test code, then verify the result with
assertEquals()to make sure your code did what it was supposed to.
They work together, not against each other—you'll often use both in the same test!
内容的提问来源于stack exchange,提问作者user1532449

