Mockito Junit 5无法抛出已检查异常。

huangapple go评论84阅读模式
英文:

Mockito Junit 5 Throw checked exception not working

问题

错误消息

org.opentest4j.AssertionFailedError: 期望抛出 java.sql.SQLException 异常,但未抛出任何异常。

	at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:71)
	at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:37)
	at org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:2952)

我希望在调用 dropRun() 时抛出异常

public interface RunRepository {
  void dropRun(List<Integer> ids) throws SQLException;
}

它的实现

public class RunRepositoryImpl implements RunRepository{
    @Override
  public void dropRun(List<Integer> ids) throws SQLException {
    //一些代码
  }
}

我想测试的类

public interface Project {

  void purge() throws SQLException;

}

以及它的实现

public ProjectImpl implements Project{
  @Override
  public void purge() throws SQLException {
    //一些代码
    try {
      runRepository.dropRun(ids);
    } catch (Exception e) {
      LOGGER.error("清除已完成的运行时出错。");
      throw e;
    }
  }
}

测试类

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kfj.repository.RunRepository;
import com.kfj.service.Project;
import java.sql.SQLException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@TestInstance(Lifecycle.PER_CLASS)
@ExtendWith(MockitoExtension.class)
public class ProjectImplTest {

  private Project project;

  @Mock
  private RunRepository runRepository;

  @BeforeEach
  public void setUp() {
    //一些代码
    project = new ProjectImpl(runRepository);
  }
    
  @Test
  public void GIVEN_non_empty_completed_runs_WHEN_purge_is_invoked_THEN_dropRun_is_invoked()
      throws SQLException {

    //MOCK Trail 1 未生效
    //doThrow(SQLException.class).when(runRepository).dropRun(any());

    //MOCK Trail 2 也未生效
    willAnswer(invocation -> {
      throw new SQLException();
    }).given(runRepository).dropRun(any());


    //Then
    assertThrows(SQLException.class, () -> project.purge());
  }

}

我尝试了一些链接,但没有成功!任何帮助将不胜感激。谢谢您。

英文:

I am trying to throw SQLException during a method call. But the exception is not thrown for some reason.

Error message

org.opentest4j.AssertionFailedError: Expected java.sql.SQLException to be thrown, but nothing was thrown.

	at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:71)
	at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:37)
	at org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:2952)

I would like the exception to be thrown when dropRun() is invoked

public interface RunRepository {
  void dropRun(List&lt;Integer&gt; ids) throws SQLException;
}

Its Implementation

public class RunRepositoryImpl implements RunRepository{
    @Override
  public void dropRun(List&lt;Integer&gt; ids) throws SQLException {
    //some piece of code
  }
}

The Class I would like to test

public interface Project {

  void purge() throws SQLException;

}

and its Implementation

public ProjectImpl implements Project{
  @Override
  public void purge() throws SQLException {
    //some piece of code
    try {
      runRepository.dropRun(ids);
    } catch (Exception e) {
      LOGGER.error(&quot;Error purging completed runs.&quot;);
      throw e;
    }
  }
}

Test class

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kfj.repository.RunRepository;
import com.kfj.service.Project;
import java.sql.SQLException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@TestInstance(Lifecycle.PER_CLASS)
@ExtendWith(MockitoExtension.class)
public class ProjectImplTest {

  private Project project;

  @Mock
  private RunRepository runRepository;

  @BeforeEach
  public void setUp() {
    //some piece of code
    project = new ProjectImpl(runRepository);
  }
    
  @Test
  public void GIVEN_non_empty_completed_runs_WHEN_purge_is_invoked_THEN_dropRun_is_invoked()
      throws SQLException {

    //MOCK Trail 1 DIDN&#39;T WORK
    //doThrow(SQLException.class).when(runRepository).dropRun(any());

    //MOCK Trail 2 DIDN&#39;T WORK either
    willAnswer(invocation -&gt; {
      throw new SQLException();
    }).given(runRepository).dropRun(any());


    //Then
    assertThrows(SQLException.class, () -&gt; project.purge());
  }

}

I tried a couple of links, but no luck!. Any help would be highly appreciated. TIA.

Link1
Link2

答案1

得分: 1

我遇到了相同的问题,以下代码无法工作。
JUnit 失败并显示以下错误:

org.mockito.exceptions.base.MockitoException: 
该方法无法使用已检查异常
无效异常javax.xml.bind.JAXBException: aa
DocumentService documentService = mock(DocumentService.class);

@Test
@DisplayName("当调用PFEL时出现错误时返回500 HTTP状态")
void handle_document_create_request_exception_in_service() {

willThrow(new JAXBException("aa")).given(documentService).generateDocument(any(DocumentCreateDto.class));

}

但是,如果我将已检查异常替换为运行时异常,它会按预期工作。

英文:

I am facing the same issue, The following code doens't work.
JUnit fails with

org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: javax.xml.bind.JAXBException: aa
DocumentService documentService = mock(DocumentService.class);

 @Test
 @DisplayName(&quot;Returns 500 http status when we have an error calling the PFEL&quot;)
 void handle_document_create_request_exception_in_service() {

 willThrow(new JAXBException(&quot;aa&quot;)).given(documentService).generateDocument(any(DocumentCreateDto.class));

}

But if I replace the CheckedExcpetion with a RunTime exception, it works as expcected

huangapple
  • 本文由 发表于 2020年10月25日 08:40:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64519322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定