我的服务其余服务中有一个函数createObject():
@Service
public class MyService {
//Repos and contructor
@Transactional
public ObjectDto createObject(Object) {
Mother mother = new Mother(name, age);
Kid kid = new Kid(name, age);
mother.addKid(kid);
this.motherRepo.saveAndFlush(mother);
Long kidId = kid.getId();
doStuffWithKidId();
return new ObjectDto()
.withMother(mother)
.withKid(kid)
.build();
}
}
我的母亲/孩子实体基本上是这样的:
@Entity
@Table("mother")
public class mother() {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id)
private Long id;
//other attributes, including @OneToMany for Kid
//Getter/Setter
}
Kid有一个类似的实体。
如您所见,该ID由数据库设置。实体中没有ID的设置器。构造函数也没有id。
现在,我要测试我的服务。我模拟了我的仓库,并想验证我的ObjectDto是否包含值,例如id。
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public MyServiceTest {
@Mock
private MotherRepo motherRepo;
@InjectMocks
private MyService myService;
@Test
void createObjectTest() {
ObjectDto expectedObjectDto = setup...;
Object inputObject = setup...;
assertThat.(this.myService.createObject(inputObject))
.isEqualToComparingFieldByField(expectedObjectDto);
}
}
预期的ObjectDto类似于
{
"motherId":1,
"motherAge":40,
"kidId":1
...
}
问题是,该ID由数据库设置。由于没有数据库,并且使用Mockito模拟了存储库,因此该值始终为null。即使将我的ExpectedObjectDto设置为null作为id,我也需要服务中“ doStuffWithKidId()”中的id。 Atm我收到NullPointerException。
是否可以设置id,例如ReflectionTestUtils.setField()?在我读过的文献中,应该始终使用模拟对服务进行测试。这是正确的还是我需要像H2这样的内存数据库?
感谢您的帮助。
答案 0 :(得分:2)
使用doAnswer
...
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
@RunWith(MockitoJUnitRunner.class)
public class MockitoSettingDatabaseIds {
private static class TestEntity {
private long id;
private String text;
public TestEntity(String text) {
this.text = text;
}
public long getId() {
return id;
}
public String getText() {
return text;
}
}
private interface TestEntityDAO {
void save(TestEntity entity);
}
private static long someLogicToTest(TestEntityDAO dao, TestEntity entity) {
dao.save(entity);
return entity.getId();
}
@Test
public void shouldReturnDatabaseGeneratedId() {
long expectedId = 12345L;
TestEntityDAO dao = mock(TestEntityDAO.class);
TestEntity entity = new TestEntity("[MESSAGE]");
doAnswer(invocation -> {
ReflectionTestUtils.setField((TestEntity) invocation.getArgument(0), "id", expectedId);
return null;
}).when(dao).save(entity);
assertThat(someLogicToTest(dao, entity)).isEqualTo(expectedId);
}
}
要回答您的评论,只需对Kid
集合执行相同的操作,例如...
doAnswer(invocation -> {
Mother toSave = (Mother) invocation.getArgument(0);
ReflectionTestUtils.setField(toSave, "id", expectedId);
for (int k = 0; k < toSave.getKids().size(); k++) {
ReflectionTestUtils.setField(toSave.getKids().get(k), "id", expectedId + k + 1);
}
return null;
}).when(dao).save(entity);
这会将id
中的Mother
设置为expectedId
,并将Kid
的ID设置为expectedId + 1
,expectedId + 2
等。