You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为createNewToken方法编写Mockito-JUnit测试用例?

Hey there! Let's start by breaking down what your createNewToken() method actually does—understanding the logic first will make writing the test way easier. Then I'll walk you through a complete Mockito-JUnit test covering all key scenarios.

Understanding Your createNewToken() Logic

Here's a plain-English breakdown of your method's flow:

  1. Check for existing token: It calls getTokenByUserToken(usertoken) to see if there's already a WebToken linked to the provided user token.
  2. Clean up old token: If an old token exists (isn't null), it removes it from the entity manager with em.remove(oldToken).
  3. Generate new token: Creates a fresh WebToken using a random UUID as its token value, and links it to the input user token.
  4. Save new token: Persists the new token to the database via em.persist(webToken).
  5. Return result: Gives back the newly generated token string.
Mockito-JUnit Test Implementation

Assuming your createNewToken() method lives in a service class (let's call it TokenService), here's a complete test class with two critical scenarios:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import javax.persistence.EntityManager;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class TokenServiceTest {

    // Mock the EntityManager to avoid hitting a real database
    @Mock
    private EntityManager em;

    // Mock the class that contains your getTokenByUserToken() method
    // Replace TokenRepository with the actual class name from your codebase
    @Mock
    private TokenRepository tokenRepo;

    // Inject our mocks into the service class we're testing
    @InjectMocks
    private TokenService tokenService;

    // Test case 1: No existing token exists for the user
    @Test
    void createNewToken_WhenNoOldTokenExists_CreatesAndReturnsValidToken() {
        String testUserToken = "test-user-123";
        
        // Mock getTokenByUserToken to return null (no old token found)
        when(tokenRepo.getTokenByUserToken(testUserToken)).thenReturn(null);
        
        // Call the method we're testing
        String newToken = tokenService.createNewToken(testUserToken);
        
        // Validate the returned token is valid
        assertNotNull(newToken);
        assertDoesNotThrow(() -> UUID.fromString(newToken)); // Ensure it's a real UUID
        
        // Verify we didn't try to delete anything (since there was no old token)
        verify(em, never()).remove(any(WebToken.class));
        
        // Verify we saved the new token with the correct user token and valid UUID
        verify(em, times(1)).persist(argThat(webToken -> 
            webToken.getUserToken().equals(testUserToken) && 
            UUID.fromString(webToken.getToken()) != null
        ));
    }

    // Test case 2: An existing token exists for the user
    @Test
    void createNewToken_WhenOldTokenExists_DeletesOldAndCreatesNewToken() {
        String testUserToken = "test-user-123";
        WebToken oldToken = new WebToken();
        oldToken.setToken("old-uuid-456");
        oldToken.setUserToken(testUserToken);
        
        // Mock getTokenByUserToken to return the existing old token
        when(tokenRepo.getTokenByUserToken(testUserToken)).thenReturn(oldToken);
        
        // Call the method under test
        String newToken = tokenService.createNewToken(testUserToken);
        
        // Validate the new token is valid and different from the old one
        assertNotNull(newToken);
        assertNotEquals(oldToken.getToken(), newToken);
        assertDoesNotThrow(() -> UUID.fromString(newToken));
        
        // Verify we deleted the old token
        verify(em, times(1)).remove(oldToken);
        
        // Verify we saved a new token linked to the user, not the old one
        verify(em, times(1)).persist(argThat(webToken -> 
            webToken.getUserToken().equals(testUserToken) && 
            !webToken.getToken().equals(oldToken.getToken())
        ));
    }
}

Key Test Details Explained

  • Mockito Annotations:
    • @Mock: Creates fake versions of dependencies (like EntityManager and TokenRepository) so we don't need a real database or external services.
    • @InjectMocks: Automatically plugs our mocked dependencies into your TokenService class.
    • @ExtendWith(MockitoExtension.class): Turns on Mockito support for JUnit 5.
  • Scenario Coverage: We test both possible paths in your method (old token exists vs doesn't exist) to make sure every line of code is validated.
  • Verification:
    • verify(em, never()).remove(...): Makes sure we don't waste time trying to delete a token that doesn't exist.
    • verify(em, times(1)).persist(...): Confirms the new token is saved exactly once.
    • argThat(...): Uses a matcher to check that the persisted WebToken has the correct user token and a valid UUID.
  • Assertions: We check that the returned token is non-null, a valid UUID, and (in the second test) not the same as the old token.

内容的提问来源于stack exchange,提问作者user6941415

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:13:18