gpt4 book ai didi

java - 如何在 sitebricks 中测试 Reply

转载 作者:行者123 更新时间:2023-11-30 08:08:54 27 4
gpt4 key购买 nike

我正在使用sitebricks,我必须使用jmock测试Reply,但该对象不是接口(interface),所以我无法模拟它。这是一些代码:

@Get
Reply<Product> view() {
return Reply.with(new Product("Anti-ageing cure"))
.as(Json.class);
}

我脑子里唯一的想法就是假装回复如下:

public class ReplyFake extends Reply{
....reply methods....
}

但我不确定这是最佳实践。

最佳答案

首先创建你自己的断言类:

public class SitebricksReplyAssertion {

public static <T> void assertIsRepliedWith(Reply<T> reply, T expected) {
assertFieldValue("entity", reply, expected);
}

public static <T> void assertThatReplyStatusIs(Reply<T> reply, int expected) {
assertFieldValue("status", reply, expected);
}

private static <T> void assertFieldValue(String fieldName, Reply reply, T expected) {
Field field = null;
try {
field = reply.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
T actual = (T) field.get(reply);
assert actual != null;

assertThat(actual, is(equalTo(expected)));
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}

}

和测试:

public class ServicesTest {

@Rule
public JUnitRuleMockery context = new JUnitRuleMockery();

@Mock
PendingUserRepository userRepository;

@Test
public void testName() throws Exception {

Services services = new Services(userRepository);

final List<PendingUserEntity> users = new ArrayList<PendingUserEntity>() {{
add(new PendingUserEntity("email", "name", "url"));
add(new PendingUserEntity("email2", "name2", "url2"));
}};

context.checking(new Expectations() {{
oneOf(userRepository).retrieveAll();
will(returnValue(users));
}});

final Reply<List<PendingUserEntity>> rep = services.getAll();

SitebricksReplyAssertion.assertThatReplyStatusIs(rep, 200);
SitebricksReplyAssertion.assertIsRepliedWith(rep,users);
}
}

和服务类别:

@At("/getpendingusers")
@Get
public Reply<List<PendingUserEntity>> getAll() {

List<PendingUserEntity> pendingUserEntities = pendingUserRepository.retrieveAll();

return Reply.with(pendingUserEntities).as(Json.class);
}

断言类的代码取自此处:https://gist.github.com/AdelinGhanaem/4072405/

关于java - 如何在 sitebricks 中测试 Reply<?>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30694147/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com