【问题标题】:How to test Reply<?> in sitebricks如何在 sitebricks 中测试回复<?>
【发布时间】:2015-06-07 13:36:25
【问题描述】:

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

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

我脑子里唯一的想法是伪造回复,例如:

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

但我不确定这是最佳做法。

【问题讨论】:

    标签: java junit sitebricks


    【解决方案1】:

    首先让你自己的断言类:

    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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-29
      • 1970-01-01
      • 2017-07-10
      • 2016-12-18
      • 1970-01-01
      相关资源
      最近更新 更多