java 未调用模拟方法

xxhby3vn  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(103)

我正在使用testng和Mockito,由于限制,我不能使用PowerMock。当我试着运行我的测试时,由于某种原因,真实的的方法被调用,而不是mock!我已经添加了一个 Package 类周围的类有静态方法。我从文档中知道Mockito不支持静态方法。因此,作为一种克服它的方法,我编写了一个简单的 Package 器,它只调用该类中的静态方法。

public class BatTrafficManagerStatsHelperTest {

    @Mock
    private MtsConfFactoryWrapper mtsConfFactoryWrapper = new MtsConfFactoryWrapper();

    private static final String EXPECTED_JSON_STR = "{"
            + "         \"duration\": 100,"
            + "         \"timestamp\": \"1970-01-01T00:00:00\","
            + "         \"cellMetrics\": {"
            + "           \"enb1_cell1\": {"
            + "             \"handoverAttempts\": 2,"
            + "             \"rrcConnectionAttempts\": 1"
            + "           }"
            + "         },"
            + "         \"trafficProfileMetrics\": {"
            + "           \"voipSpeech_2PDN\": {"
            + "             \"srMtSuccess\": 4,"
            + "             \"numberOfUEs\": 100,"
            + "             \"srMoSuccess\": 3,"
            + "             \"attachSuccess\": 5,"
            + "             \"rrcConnectionAttempts\": 1"
            + "           }"
            + "         },"
            + "         \"ueGroupMetrics\": {"
            + "           \"ueGroup1\": {"
            + "             \"handoverAttempts\": 2,"
            + "             \"numberOfUEs\": 100,"
            + "             \"rrcConnectionAttempts\": 1"
            + "           }"
            + "         }"
            + "       }";

    @BeforeMethod
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    /**
     * getBstmString()
     * Setup mock, tests getBstmString() and verify result
     *
     * @throws Exception
     */
    @Test
    public void testGetBtmString() throws Exception {
        final Date date = Mockito.mock(Date.class);
        Mockito.when(date.getTime()).thenReturn(0L);

        final Map<OptimizedRoute, List<StatsQueue>> ueStatsTrackerMock = getUeStatsTrackerMock();
        final Map<Enb, List<OptimizedCellStatsQueue>> cellStatsTrackerMock = getCellStatsTrackerMock();
        final MtsConfBuilder confBuilderMock = Mockito.mock(MtsConfBuilder.class);
        final Tracker trackerMock = Mockito.mock(Tracker.class);

        Mockito.when(mtsConfFactoryWrapper.getConfBuilderr()).thenReturn(confBuilderMock);
        Mockito.when(confBuilderMock.getTracker()).thenReturn(trackerMock);
        Mockito.when(trackerMock.getUeStatsTracker()).thenReturn(
                ueStatsTrackerMock);
        Mockito.when(trackerMock.getCellStatsTracker()).thenReturn(
                cellStatsTrackerMock);
        Mockito.when(trackerMock.getConfiguredTrafficProfiles())
                .thenReturn(
                        getFakeTrafficProfilesList());

        BatTrafficManagerStatsHelper btmStatsHelper = new BatTrafficManagerStatsHelper(date);
        String result = btmStatsHelper.getBtmString(TIME).replace("JsonDataForBatTrafficManagerRegex:", "");

        JsonParser parser = new JsonParser();
        assertEquals(parser.parse(result), parser.parse(EXPECTED_JSON_STR));
    }

}

测试中原始类如下所示

public class BatTrafficManagerStatsHelper {

    private final Date date;

    /*
     * Constants for BAT Traffic Manager log parsing
     */
    private static final ImmutableMap<String, String> AHL_STATS_CONSTANTS_TO_BTM_CONSTANTS = ImmutableMap.of(
            BatAeroflexHLStatsConstants.RRC_CONNECTION_REQUEST_ATTEMPTS, "rrcConnectionAttempts",
            BatAeroflexHLStatsConstants.HANDOVER_ATTEMPTS, "handoverAttempts",
            BatAeroflexHLStatsConstants.SERVICE_REQ_MO_SUCCESS, "srMoSuccess",
            BatAeroflexHLStatsConstants.SERVICE_REQ_MT_SUCCESS, "srMtSuccess",
            BatAeroflexHLStatsConstants.ATTACH_SUCCESS, "attachSuccess");
    private static final String NUMBER_OF_UES = "numberOfUEs";

    /**
     * Constructor
     *
     * @param date
     */
    public BatTrafficManagerStatsHelper(Date date) {
        this.date = new Date(date.getTime());
    }

    /**
     * Extracts log data and returns it in a format suited
     * for parsing in {@literal BAT Traffic Manager}.
     *
     * @param elapsedTime
     * @return log data for BAT Traffic Manager
     */
    public String getBtmString(long elapsedTime) {
        MtsConfFactoryWrapper mtsConfFactoryWrapper = new MtsConfFactoryWrapper();
        Map<OptimizedRoute, List<StatsQueue>> ueGroupTracker = mtsConfFactoryWrapper.getConfBuilderr().getTracker()
                .getUeStatsTracker();
        Map<Enb, List<OptimizedCellStatsQueue>> cellTracker = mtsConfFactoryWrapper.getConfBuilderr().getTracker()
                .getCellStatsTracker();

        BatTrafficManagerStatsHelperJson json = new BatTrafficManagerStatsHelperJsonBuilder()
                .setDuration(elapsedTime)
                .setTimestamp(getTimeStamp())
                .setCellMetrics(getCellMetrics(cellTracker))
                .setTrafficProfileMetrics(getTrafficProfileMetrics(ueGroupTracker))
                .setUeGroupMetrics(getUeGroupMetrics(ueGroupTracker))
                .build();

        return "JsonDataForBatTrafficManagerRegex:" + getJsonString(json);
    }

}

public class MtsConfFactoryWrapper  {
    public MtsConfFactoryWrapper() {}

    public MtsConfBuilder getConfBuilderr() {
        return MtsConfFactory.getConfBuilder();
    }
}
xlpyo6sf

xlpyo6sf1#

在你的测试课上使用这个,

@Mock
private MtsConfFactoryWrapper mtsConfFactoryWrapper;

而不是

@Mock
private MtsConfFactoryWrapper mtsConfFactoryWrapper = new MtsConfFactoryWrapper();

你不应该给mtsConfFactoryWrapper变量赋值一个新对象。当MockitoAnnotations.initMocks(this);被调用时,一个mock对象将被分配给mtsConfFactoryWrapper变量。
在你的方法中,你总是像下面这样创建一个新对象,
MtsConfFactoryWrapper mtsConfFactoryWrapper = new MtsConfFactoryWrapper();
因此,即使你在测试中模拟了对象,当方法被调用时,它也会再次创建一个新对象。尝试将其注入到类中,而不是在方法内部创建新示例。
你的类应该是这样的

public class BatTrafficManagerStatsHelper {

    private MtsConfFactoryWrapper mtsConfFactoryWrapper;

    public BatTrafficManagerStatsHelper(MtsConfFactoryWrapper mtsConfFactoryWrapper) {
        this.mtsConfFactoryWrapper = mtsConfFactoryWrapper;
    }

    // other stuffs
}

在测试类中,当您创建BatTrafficManagerStatsHelper对象时,将mock对象传递给构造函数,如下所示:

public class BatTrafficManagerStatsHelperTest {
    @Test
    public void testGetBtmString() throws Exception {
        //your code

        BatTrafficManagerStatsHelper btmStatsHelper = new BatTrafficManagerStatsHelper(passYourMockedObjectHere);
    }
}

相关问题