如何使用反射设置值

huangapple 未分类评论61阅读模式
标题翻译

how to set value with reflection

问题

我正在为一个方法编写 J-unit 测试用例。

A.java

     void resetToolbar(final ListSelectionModel lastSelectionModel) {
            // 尝试恢复上一页
            if (toolbar != null && lastSelectionModel != null) {
                gridPanel.setSelectionModel(lastSelectionModel);
            }
           // 问题出现在这里..... 在 PagingToolbar 中。
            toolbar = new PagingToolbar();
        }

PagingToolbar.java

    class PagingToolbar {
    private I18nUtils i18n;   // 这是一个类,我应该如何模拟这些。i18n

    /**
     * 创建一个新的分页工具栏。
     */
    public PagingToolbar() {
        super();
        setDisplayingItemsText(i18n.getText(this, "facebook")); 
    // 这里 i18n 为 null 并且抛出了空指针异常。
}

ATest.java

    @Test(groups = { "unit" })
    public class ATest {
        @Test
        public void resetToolbar(){
    
            I18nUtils i18n = createNiceMock(I18nUtils.class);
    
            // 调用
            A tt = new A();

            // 如何使用反射在 pagingToolbar 中设置 i18n。
            tt.resetToolbar(listselectmodelMock);
        }
    }

注意:在 A 类的 resetToolbar() 方法中,我必须使用 new 关键字调用 pagingToolbar。
英文翻译

I am writing J-unit test case for one my method.

A.java

 void resetToolbar(final ListSelectionModel lastSelectionModel) {
        // attempt to restore the previous page
        if (toolbar != null && lastSelectionModel != null) {
            gridPanel.setSelectionModel(lastSelectionModel);
        }
       // Issue occur here..... In PagingToolbar.
        toolbar = new PagingToolbar();
    }

PagingToolbar.java

class PagingToolbar {
private I18nUtils i18n;   //It is a class How should I mock these. i18n

/**
 * Creates a new paging toolbar.
 */
public PagingToolbar() {
    super();
    setDisplayingItemsText(i18n.getText(this, "facebook")); 
// here i18n get null and throws null pointer-exception.

}

ATest.java

@Test(groups = { "unit" })
public class ATest {
    @Test
    public void resetToolbar(){

        I18nUtils i18n = createNiceMock(I18nUtils.class);

        // Invoke
        A tt = new A();

        // How to set i18n with reflection in pagingToolbar.
        tt.resetToolbar(listselectmodelMock);
    }
}

NOTE : In A class in resetToolbar() , I have to invoke pagingToolbar with new keyword.

huangapple
  • 本文由 发表于 2020年1月30日 18:58:49
  • 转载请务必保留本文链接:https://java.coder-hub.com/59984446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定