简体   繁体   中英

How to unit test a method which has a return value and dependent on my other class?

I'm a newbie at java unit testing. How to unit test a method which has a return value and dependent on my other class?

The following codes convert a ResponseBody to an object. The parser.fromJson(json, type) and decodeToJson(value) are my custom mthods. How should I unit test the method convert(ResponseBody) ?

public class MyConverter<T> {
    public MyConverter(JsonParser parser, Type type, Cipher  cipher) {
        this.parser = parser;
        this.type = type;
        this.cipher = cipher;
    }

    public T convert(ResponseBody value) throws IOException {
        String json;
        if (cipher == null) {
            json = value.string();
        } else {
            json = decrypt(value);
        }
        return parser.fromJson(json, type);
    }

    public String decrypt(ResponseBody value) {
        //Just decrypt the ResponseBody to String.
        ...
    }
}

I already have some test codes. Here is my test case.

@Test
public void testConvert_withCipher() throws Exception {
    converter = spy(new MyConverter(mockParser, mockType, null));
    ResponseBody dummyResponse = ResponseBody.create(MediaType.parse("application/json"), "{text:'Dummy response'}");

    converter.convert(dummyResponse);

    verify(converter).decrypt(eq(dummyResponse));
    verify(mockParser).fromJson(anyString(), eq(mockType));
}

I only verify the vital dependent mock objects were interacted with correctly. Should I verify the returned value?

Hope someone can help me, thanks!

You can use any of the Mocking Frameworks like Mockito or JMock to mock the Response.

You don't have to verify the actual value returned from JsonParser since you are not writing the Unit Test for JsonParser but your class.

If you want to verify the number of times any of your mock has been called then you can do something like this:

verify(converter, Mockito.times(1)).decrypt(eq(dummyResponse));

This will fail in case your mock has not been called at all or is called more than one time.

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