簡體   English   中英

使用Spring,JUNIT,MockMvc和Hamcrest測試控制器

[英]Testing controllers using Spring, JUNIT, MockMvc and Hamcrest

我正在嘗試測試我的控制器,該控制器在get方法上返回一個對象列表,以在頁面上填充一個下拉列表。

我正在嘗試使用MockMvc和Hamcrest編寫JUnit測試來測試相同的測試。

我想比較對象列表並測試它是否失敗。

我已經在Test.java中創建了一個靜態對象列表,並且正在從model.attribute方法中獲取一個對象列表。

測試:兩個對象列表是否相等且不包含任何其他對象。

我的對象稱為Option,它具有3個屬性。 鍵,值和選定的。 我必須檢查列表中是否存在所有鍵。

我無法創建匹配器來執行相同操作。 我正在嘗試創建一個匹配器來比較我的列表。

到目前為止,我已經執行了以下操作:

@Before
public void setup() throws Exception {
    // This would build a MockMvc with only the following controller
    this.mockMvc = MockMvcBuilders.standaloneSetup(openAccountController)
            .build();
}

@Test
public void testOpenAccount() {
    try {
        setAllLegislations();
        this.mockMvc
                .perform(get("/open_account.htm"))
                // This method is used to print out the actual httprequest
                // and httpresponse on the console.
                .andDo(print())
                // Checking if status is 200
                .andExpect(status().isOk())
                .andExpect(
                        model().attributeExists("appFormAccountPlans",
                                "appFormLiraLegislations",
                                "appFormLrspLegislations",
                                "appFormRlspLegislations"))
                .andExpect(
                        model().attribute("appFormAccountPlans", hasSize(5)))
                .andExpect(
                        model().attribute("appFormLiraLegislations",
                                hasSize(8)))
                .andExpect(
                        model().attribute("appFormLrspLegislations",
                                hasSize(2)))
                .andExpect(
                        model().attribute("appFormRlspLegislations",
                                hasSize(1)))
                .andExpect(
                        model().attribute(
                                "appFormLiraLegislations",
                                hasKeyFeatureMatcher(getLiraLegislations(allLegislations))));


private Matcher<List<Option>> hasKeyFeatureMatcher(
        final List<Option> expectedOptions) {
    return new FeatureMatcher<List<Option>, List<Option>>(
            equalTo(expectedOptions), "Options are", "was") {

        @Override
        protected List<Option> featureValueOf(List<Option> actualOptions) {
            boolean flag = false;
            if (actualOptions.size() == expectedOptions.size()) {
                for (Option expectedOption : expectedOptions) {
                    for (Option actualOption : actualOptions) {
                        if (expectedOption.getKey().equals(
                                actualOption.getKey())) {
                            flag = true;
                        } else {
                            flag = false;
                            break;
                        }
                    }
                }
            }
            if (flag)
                return actualOptions;
            else
                return null;
        }
    };
}

private List<Option> getLiraLegislations(List<Option> legislation) {

    List<Option> liraLegislations = new ArrayList<Option>();
    Iterator<Option> iterator = legislation.iterator();
    while (iterator.hasNext()) {
        Option option = iterator.next();
        if (LIRA_LEGISLATIONS.contains(option.getKey())) {
            liraLegislations.add(option);
        }
    }
    return liraLegislations;
}

private List<Option> allLegislations;

public List<Option> getAllLegislations() {
    return allLegislations;
}

public void setAllLegislations() {
    allLegislations = new ArrayList<Option>();
    for (String key : ALL_LEGISLATIONS) {
        Option option = new Option();
        option.setKey(key);
        allLegislations.add(option);
    }
}

private static final Set<String> ALL_LEGISLATIONS = new HashSet<String>(
        Arrays.asList(AccountLegislationEnum.AB.toString(),
                AccountLegislationEnum.MB.toString(),
                AccountLegislationEnum.NB.toString(),
                AccountLegislationEnum.NL.toString(),
                AccountLegislationEnum.NS.toString(),
                AccountLegislationEnum.ON.toString(),
                AccountLegislationEnum.QC.toString(),
                AccountLegislationEnum.SK.toString(),
                AccountLegislationEnum.BC.toString(),
                AccountLegislationEnum.FE.toString(),
                AccountLegislationEnum.NT.toString(),
                AccountLegislationEnum.PE.toString(),
                AccountLegislationEnum.YT.toString(),
                AccountLegislationEnum.NU.toString(),
                AccountLegislationEnum.UNKNOWN.toString()));

這就是我將模型屬性獲取為的方式:

 Attribute = appFormLiraLegislations
           value = [com.abc.arch.core.gui.eform.gui.Option@199d1739, com.abc.arch.core.gui.eform.gui.Option@185fac52, com.abc.arch.core.gui.eform.gui.Option@312a47fe, com.abc.arch.core.gui.eform.gui.Option@4edc8de9, com.abc.arch.core.gui.eform.gui.Option@71e8e471, com.abc.arch.core.gui.eform.gui.Option@70edf123, com.abc.arch.core.gui.eform.gui.Option@15726ac1, com.abc.arch.core.gui.eform.gui.Option@abeafe7]

提前致謝。

當您使用key屬性正確實現Option對象hashCode()equals()方法時,可以使您的生活變得更加輕松。 那么您可以簡單地寫:

model().attribute("appFormLiraLegislations",getLiraLegislations(allLegislations)))

並依靠list1.equals(list2)方法為您完成工作。

選項hashCodeequals實現:

public class Option {

    private String key;
    private String label;

    ...

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((key == null) ? 0 : key.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Option other = (Option) obj;
        if (key == null) {
            if (other.key != null)
                return false;
        } else if (!key.equals(other.key))
            return false;
        return true;
    }

}

上面的方法是由我的IDE生成的。 我也不知道您的Option類的確切結構是什么,因此除了key屬性之外,我還添加了label屬性。

我創建了一個自定義的Hamcrest匹配器,以通過檢查大小和鍵來比較“選項列表”。

private Matcher<List<Option>> hasOptionsFeatureMatcher(
        final List<Option> expectedOptions) {
    return new FeatureMatcher<List<Option>, List<Option>>(
            equalTo(expectedOptions), "Options are", "Options were") {

        @Override
        protected List<Option> featureValueOf(List<Option> actualOptions) {
            boolean flag = false;
            if (expectedOptions.size() == actualOptions.size()) {
                for (Option expected : expectedOptions) {
                    for (Option actual : actualOptions) {
                        if (expected.getKey().equals(actual.getKey())) {
                            flag = true;
                            break;
                        } else {
                            flag = false;
                        }
                    }
                }
            } else
                flag = false;
            if (flag)
                return expectedOptions;
            else
                return null;
        }

    };

實施如下:

private static final ImmutableBiMap<String, String> LIRA = new ImmutableBiMap.Builder<String, String>()
        .put(AccountLegislationEnum.AB.toString(), "ALBERTA")
        .put(AccountLegislationEnum.MB.toString(), "MANITTOBA")
        .put(AccountLegislationEnum.NB.toString(), "NEW BRUNSWICK")
        .put(AccountLegislationEnum.NL.toString(), "NEWFOUNDLAND")
        .put(AccountLegislationEnum.NS.toString(), "NOVA SCOTIA")
        .put(AccountLegislationEnum.ON.toString(), "ONTARIO")
        .put(AccountLegislationEnum.QC.toString(), "QUEBEC")
        .put(AccountLegislationEnum.SK.toString(), "SASKATCHEWAN")
        .put(AccountLegislationEnum.UNKNOWN.toString(), "UNKNOWN").build();

private List<Option> prepareOptions(ImmutableBiMap<String, String> map) {
    List<Option> legislations = new ArrayList<Option>();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        Option option = new Option();
        option.setKey(key);
        option.setValue(value);
        legislations.add(option);
    }
    return legislations;
}


.andExpect(model().attribute("appFormLiraLegislations",hasOptionsFeatureMatcher(prepareOptions(LIRA))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM