简体   繁体   中英

How to Mock an Enum Class using Mockito 2

This application is developed using Spring Boot. I have a controller class named BridgeController where I'm performing a POST call.

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

Service Class named BridgeService where it is having a method named status and inside this method, I have used "Status" which is an enum class.

@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;
}

This is my Test Class

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");  
    }
}

My Enum is public enum Status {

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;
}

} Getting an exception at 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.

Can anyone help me in fixing this issue?

The problem is you are trying to mock static methods. You won't be able

Why doesn't Mockito mock static methods?

You might want to use Dependency Injection more broadly. Anyway, if still you really want to follow that path, use Powermockito

Mocking static methods with Mockito

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM