2015-06-07 18 views
1

我正在使用sitebricks,我必須使用jmock測試Reply,但該對象不是接口,所以我不能嘲笑它。下面是一些代碼:如何測試回覆<?> in sitebricks

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

唯一的想法在我頭腦是假的回覆是這樣的:

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

,但我不知道這是最好的做法。

回答

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/

相關問題