Skip to content

Incorrect mocks are created for test with ToStringCreator.append #2158

Open
@EgorkaKulikov

Description

@EgorkaKulikov

Description

Generate tests for toString method from https://github.com/spring-projects/spring-petclinic/blob/main/src/main/java/org/springframework/samples/petclinic/owner/Owner.java with standard settings.

You may also use the simplified version of this method

@Override
public String toString() {
    return new ToStringCreator(this).append("id", this.getId())
	.append("new", this.isNew())
	.append("lastName", this.getLastName())
	.append("firstName", this.getFirstName())
	.append("address", this.address)
	.append("city", this.city)
	.append("telephone", this.telephone)
	.toString();
}

Actual behavior

One of generated tests fails the assertion.

@Test
	@DisplayName("toString: ToStringCreatorAppend -> return new ToStringCreator(this).append(\"address\", this.address).append(\"city\", this.city).append(\"telephone\", this.telephone).toString()")
	public void testToString_ToStringCreatorToString() {
		org.mockito.MockedConstruction mockedConstruction = null;
		try {
			ToStringCreator toStringCreatorMock1 = mock(ToStringCreator.class);
			ToStringCreator toStringCreatorMock2 = mock(ToStringCreator.class);
			ToStringCreator toStringCreatorMock3 = mock(ToStringCreator.class);
			(when(toStringCreatorMock2.append(any(String.class), any(Object.class)))).thenReturn(toStringCreatorMock3);
			(when(toStringCreatorMock2.toString())).thenReturn(((String) null));
			(when(toStringCreatorMock1.append(any(String.class), any(Object.class)))).thenReturn(toStringCreatorMock2);
			mockedConstruction = mockConstruction(ToStringCreator.class, (ToStringCreator toStringCreatorMock, org.mockito.MockedConstruction.Context context) -> (when(toStringCreatorMock.append(any(String.class), any(Object.class)))).thenReturn(toStringCreatorMock1));
			Owner owner = new Owner();
			String string = "";
			owner.setAddress(string);
			owner.setCity(string);
			owner.setTelephone(string);

			String actual = owner.toString();

			assertNull(actual);
		} finally {
			mockedConstruction.close();
		}
	}

Additional context

The problem was hidden by some bugs in MockValueConstructor, see #2157 for more details.

Metadata

Metadata

Assignees

Labels

comp-codegenIssue is related to code generatorcomp-springIssue is related to Spring projects supportctg-bugIssue is a bug

Type

No type

Projects

Status

Todo

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions