当前位置: 首页 > 知识库问答 >
问题:

如何解决“要创建新的mock,必须撤销已有的mock注册”

葛驰
2023-03-14
 @ExtendWith(MockitoExtension.class)
// @PrepareForTest(UserContext.class)
public class KonfigurationCopyServiceTest {

  public static final String CONFIGURATION_NAME = "Standard-Konfiguration";

  @Mock
  public TriggeringKonfigurationService triggeringKonfigurationService;
  @Mock
  public ReportKonfigService reportConfigurationService;
  @Mock
  public BuchungsschemaService buchungsschemaService;

  public KonfigurationCopyService copyService;

  @BeforeEach
  public void init() {
    Mockito.mockStatic(UserContext.class);
    Mockito.when(UserContext.getUsername()).thenReturn("superuser");

    copyService = new KonfigurationCopyService(triggeringKonfigurationService,
        reportConfigurationService, buchungsschemaService);
  }

谢谢你!

编辑:UserContext.java

package de.msggillardon.system;

/**
 * This class contains the username and IP-address of the logged in user. It is initialized for each
 * session.
 *
 * @author wildp
 */
public class UserContext {

  private static final ThreadLocal<UserContext> userContext = new ThreadLocal<>();

  private final String username;

  private final String clientIPAddress;

  /**
   * Constructor.
   *
   * @param username        Username of the user who is logged in
   * @param clientIPAddress IP Address of the user who is logged in
   */
  public UserContext(String username, String clientIPAddress) {
    this.username = username;
    this.clientIPAddress = clientIPAddress;
  }

  /**
   * Initializes the threadLocal
   *
   * @param userContext
   */
  public static void initialize(UserContext userContext) {
    UserContext.userContext.set(userContext);
  }

  /**
   * Removes the current thread's value for this thread-local variable.
   */
  public static void remove() {
    userContext.remove();
  }

  /**
   * Returns the username of the current thread.
   *
   * @return
   */
  public static String getUsername() {
    return userContext.get().username;
  }

  /**
   * Returns the IP address of the client of the current thread.
   *
   * @return
   */
  public static String getClientIPAddress() {
    return userContext.get().clientIPAddress;
  }

  public static UserContext getThreadLocalUserContext(){
    return userContext.get();
  }
}

新编辑:我再次编辑了我的代码,所以您现在可以看到,我正在使用@ExtendWith(mockitoExtension.lass)来模拟。

共有1个答案

满俊楠
2023-03-14

因此,当我使用JUnit5时,我不能使用@before注释,所以我用@beforeall替换了@beforeach。所以我是这样做的:

  1. 步骤:导入
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;

步骤:添加@TestInstance(PER_CLASS)注释(在类之前)

 类似资料: