【问题标题】:How to Mock an Enum Class using Mockito 2如何使用 Mockito 2 模拟枚举类
【发布时间】:2020-05-25 17:57:49
【问题描述】:

此应用程序是使用 Spring Boot 开发的。我有一个名为 BridgeController 的控制器类,我在其中执行 POST 调用。

@PostMapping(path = STATUS, produces = MediaType.APPLICATION_JSON)
public Response status(@RequestBody final Request request) {
    return this.bridgeService.status(request);
}

名为 BridgeService 的服务类,它有一个名为 status 的方法,在此方法中,我使用了“Status”,它是一个枚举类。

@Override
public Response status(final request request) {
    final String id = request.getId();
    final Response response = Response.build();
    final Status status = Status.fromId(mappings.getId());
    if (null == status) {
        response.setStatus(RequestStatus.FAILURE);
        response.setStatusMsg(
                "Unable to find a valid mapping for the status id : " + mappings.getStatusId());
    } else {
        response.setResponse(status.getName());
    }
    return response;
}

这是我的测试课

public class BridgeControllerTest extends BaseTest {
    MockMvc mockMvc;

    @Autowired
    WebApplicationContext context;

    @InjectMocks
    BridgeController bridgeController;

    @MockBean
    request request;

    @Mock
    Status status;

    @Mock
    BridgeService bridgeService;

    ObjectMapper objmapper = new ObjectMapper();

    @Before
    public  void setUp(){
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void statusSuccessTest() throws JsonProcessingException, Exception{  
        Mappings mappings = Mappings.build();
        when(statusRequest.getId()).thenReturn("12345");
        when(Status.fromId(mappings.getStatusId())).thenReturn(status);
        MvcResult result=this.mockMvc.perform(post("/status")
                .content(objmapper.writeValueAsString(request))
                .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andReturn();
        String resultContent = result.getResponse().getContentAsString();      
        AppResponse appResponse = objmapper.readValue(resultContent, Response.class);
        assertEquals("Request processed successfully", Response.getStatusMsg());
        Assert.assertTrue(Response.getStatus().getValue()=="SUCCESS");  
    }
}

我的枚举是 公共枚举状态 {

PENDING(1, "PENDING"), CONFIRMED(2, "CONFIRMED"), DECLINED(3, "DECLINED");

private final int id;

private final String name;

Status(final int id, final String name) {
    this.id = id;
    this.name = name;
}
public int getId() {
    return this.id;
}
public String getName() {
    return this.name;
}

@JsonCreator
public static Status fromId(final int id) {
    for (final Status status : Status.values()) {
        if (status.getId() == id) {
            return status;
        }
    }
    return null;
}

} 在when(AAStatus.fromId(requestMappings.getStatusId())).thenReturn(null); 处获得异常

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
    Those methods *cannot* be stubbed/verified.
    Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

谁能帮我解决这个问题?

【问题讨论】:

  • 你不能模拟一个枚举。
  • 是的,你不能为 final 类创建模拟,enum 只是 final 类的一个特例。
  • 你为什么要模拟一个枚举类?为什么不使用 Enum 本身?
  • 我知道我们可以使用 Mockito 2 模拟枚举
  • 请考虑您的 static 方法永远不应该在有效场景中返回 null。你想在这里测试什么?

标签: java spring-boot mockito junit4


【解决方案1】:

问题是您正在尝试模拟静态方法。你将无法

Why doesn't Mockito mock static methods?

您可能希望更广泛地使用依赖注入。无论如何,如果您仍然真的想走这条路,请使用 Powermockito

Mocking static methods with Mockito

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-03
    • 2015-07-19
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多