How do you Test Getter and Setter Interface in Java using Mockit

  • 时间:2020-09-08 11:08:55
  • 分类:网络文摘
  • 阅读:82 次

Usually, we unit tests the logics. An interface is without implementation details. A interface is just a binding a contract, but still, we can use Mockito to mock the interface, and test it.

For example, given the following simple Setter and Getter Interface:

1
2
3
4
interface GetAndSet {
    void setValue(String name);
    String getValue();
}
interface GetAndSet {
    void setValue(String name);
    String getValue();
}

We can test it like this – thanks to the Mockito mocking framework in Java. We use doAnswer method to intercept the invokation of a interface method i.e. setter, then at the time, we mock the getter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.helloacm;
 
import lombok.val;
import org.junit.jupiter.api.Test;
 
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
 
interface GetAndSet {
    void setValue(String name);
    String getValue();
}
 
public class ExampleTest {
    @Test
    public void test_simple_getter_setter_interface() {
        val instance = mock(GetAndSet.class);
 
        doAnswer(invocation -> {
            // or use invocation.getArgument(0);
            val name = (String)invocation.getArguments()[0];
            when(instance.getValue()).thenReturn(name);
            return null;
        }).when(instance).setValue(anyString());
 
        instance.setValue("HelloACM.com");
        assertEquals("HelloACM.com", instance.getValue());
    }
}
package com.helloacm;

import lombok.val;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;

interface GetAndSet {
    void setValue(String name);
    String getValue();
}

public class ExampleTest {
    @Test
    public void test_simple_getter_setter_interface() {
        val instance = mock(GetAndSet.class);

        doAnswer(invocation -> {
            // or use invocation.getArgument(0);
            val name = (String)invocation.getArguments()[0];
            when(instance.getValue()).thenReturn(name);
            return null;
        }).when(instance).setValue(anyString());

        instance.setValue("HelloACM.com");
        assertEquals("HelloACM.com", instance.getValue());
    }
}

If the method we are mocking is not void – we can use when. For example:

1
2
3
when(instance.getValue()).thenAnswer(innocation -> {
     return "Hello";
});
when(instance.getValue()).thenAnswer(innocation -> {
     return "Hello";
});

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
食物为何会致癌及常见致癌物来源  肯德基麦当劳可食用冰块菌落超标  南瓜的保健作用:降血糖血脂、防癌  大暑养生:暑天应多吃清淡易消化食物  市场热俏的功能性饮料到底是什么?  不能把功能性饮料完全代替饮用水  功能性饮料应该如何科学合理的饮用  网传的10种致癌食物中有9种不靠谱  夏季常见水果:西瓜的营养保健价值  健康食品黑枣的食疗功效与营养价值 
评论列表
添加评论