【发布时间】:2020-08-04 18:10:42
【问题描述】:
tl;博士: 似乎我使用关于 save 方法的自定义行为创建的存储库的 Mock 在注入时会丢失自定义行为。
问题描述
我一直在尝试在 Spring 中测试服务。特别感兴趣的方法采用一些参数并创建一个 User,该 User 通过存储库方法 save 保存到 UserRepository 中。
我感兴趣的测试是将这些参数与传递给存储库的 save 方法的 User 的属性进行比较,然后检查它是否是正确添加新用户。
为此,我决定模拟存储库并将相关服务方法传递的参数保存到存储库 save 方法。
我基于myself on this question 来保存用户。
private static User savedUser;
public UserRepository createMockRepo() {
UserRepository mockRepo = mock(UserRepository.class);
try {
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
savedUser= (User) invocation.getArguments(0);
return null;
}
}).when(mockRepo).save(any(User.class));
} catch( Exception e) {}
return mockRepo;
}
private UserRepository repo = createMockRepo();
两个音符:
-
我提供了名称 repo,以防名称必须与服务中的名称匹配。
-
没有 @Mock 注释,因为它开始无法通过测试,我认为这是因为它将以通常的方式创建一个模拟(没有我之前创建的自定义方法)。
然后我创建了一个测试函数来检查它是否具有所需的行为并且一切都很好。
@Test
void testRepo() {
User u = new User();
repo.save(u);
assertSame(u, savedUser);
}
然后我尝试按照我在多个问题中看到的建议进行操作,即将模拟注入服务,如here 所述。
@InjectMocks
private UserService service = new UserService();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
这就是问题出现的地方,当我尝试访问 savedUser 属性时,我为其创建的测试会引发 null 异常(这里我简化了用户属性,因为似乎不是原因)。
@Test
void testUser() {
String name = "Steve";
String food = "Apple";
service.newUser(name, food);
assertEquals(savedUser.getName(), name);
assertEquals(savedUser.getFood(), food);
}
调试时:
- 服务似乎已收到模拟:debugged properties of the service
- savedUser 确实是 null:debugged savedUser propert。
出于演示目的,我决定使用 System.out.println 记录该函数。
A print of my logging of the tests, demonstrating that the user test doesn't call the answer method
我在这里做错了什么?
提前感谢您的帮助,这是我的第一个堆栈交换问题,非常感谢任何改进提示。
【问题讨论】:
标签: java spring unit-testing junit mockito