我怎样才能通过测试?

时间:2016-03-18 02:13:00

标签: java

我如何让构造函数将其参数存储到实例变量句中?我需要使用新的运算符吗?

public class SentenceCounter
{
public String sentence;

    public SentenceCounter(String sentence)
    {

    }

    public Object getSentence()
    {

        return sentence;
    }

}
public class TestSentenceCounter {

        private static final String SENTENCE1 =
                "This is my sentence.";
        private static final String SENTENCE2 =
                "These words make another sentence that is longer";
        private SentenceCounter sc1;
        private SentenceCounter sc2;

        /**
         * Create two instance variable is correct
         */
        @Before
        public void setup()
        {
         sc1 = new SentenceCounter(SENTENCE1);
         sc2 = new SentenceCounter(SENTENCE2);
        }
        /** 
         * Make sure the instance variable is correct 
         */

    @Test
    public void testConstructor()
    {
        assertEquals(SENTENCE1, sc1.getSentence());
        assertEquals(SENTENCE2, sc2.getSentence());
    }

}

2 个答案:

答案 0 :(得分:2)

  

我如何让构造函数将其参数存储到实例中   变句?

public class SentenceCounter
{
public String sentence;

    public SentenceCounter(String sentence)
    {
        this.sentence = sentence; // This is how
    }

    public Object getSentence()
    {

        return sentence;
    }

}

在您的代码中,您不使用构造函数参数来初始化sentence变量。

使用this.sentence = sentence语句,问题得到解决。因此,您的测试将通过。问题不在测试中,在SentenceCounter类构造函数中。

答案 1 :(得分:1)

在构造函数中,您将重命名参数变量名称或使用this.variable。

public SentenceCounter(String sentence) {
    this.sentence = sentence;
}

public SentenceCounter(String s) {
    sentence = s;
}