001/* 002 * Copyright 2023 the original author or authors. 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package de.cuioss.test.valueobjects.contract; 017 018import static org.junit.jupiter.api.Assertions.assertNotNull; 019 020import de.cuioss.test.valueobjects.api.object.ObjectTestConfig; 021import de.cuioss.test.valueobjects.api.object.ObjectTestContract; 022import de.cuioss.test.valueobjects.objects.ParameterizedInstantiator; 023import de.cuioss.tools.logging.CuiLogger; 024import lombok.RequiredArgsConstructor; 025 026/** 027 * Checks whether the object in hand implements {@link Object#toString()} and 028 * calls it will fully populated object. 029 * 030 * @author Oliver Wolff 031 */ 032@RequiredArgsConstructor 033public class ToStringContractImpl implements ObjectTestContract { 034 035 private static final CuiLogger log = new CuiLogger(ToStringContractImpl.class); 036 037 @Override 038 public void assertContract(final ParameterizedInstantiator<?> instantiator, 039 final ObjectTestConfig objectTestConfig) { 040 041 final var builder = new StringBuilder("Verifying "); 042 builder.append(getClass().getName()).append("\nWith configuration: ").append(instantiator.toString()); 043 log.info(builder.toString()); 044 Object target; 045 046 if (shouldUseMinimal(objectTestConfig) 047 && !instantiator.getRuntimeProperties().getWritableProperties().isEmpty()) { 048 target = instantiator.newInstanceMinimal(); 049 } else { 050 target = instantiator.newInstance(instantiator.getRuntimeProperties().getWritableAsPropertySupport(true), 051 false); 052 } 053 ReflectionUtil.assertToStringMethodIsOverriden(target.getClass()); 054 assertNotNull(target.toString(), "toString must not return 'null'"); 055 } 056 057 static boolean shouldUseMinimal(final ObjectTestConfig objectTestConfig) { 058 return null != objectTestConfig && objectTestConfig.toStringUseMinimalInstance(); 059 } 060 061}