Я пытаюсь проверить мой контроллер, который возвращает мне список объектов метода get для заполнения раскрывающегося списка на моей странице.Контрольные контроллеры, использующие Spring, JUNIT, MockMvc и Hamcrest
Я пытаюсь написать тест JUnit, используя MockMvc и Hamcrest, чтобы проверить их.
Я хочу сравнить список объектов и проверить, не терпит неудачу или нет.
Я создал статический список объектов в своем 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 = [[email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]]
Спасибо заранее.
Можете ли вы объяснить мне, как бы это идти? Извините, у меня есть туннельное видение, борясь с этой проблемой. – Shashank
Спасибо @Pavla, я никогда не думал сравнивать это! Работал как шарм! – Shashank
Есть ли способ, чтобы не использовать вышеуказанный способ и выполнить это? Это изменит мой производственный код, и я стараюсь избегать этого! Пожалуйста, предложите мне способ! – Shashank