【问题标题】:How to write a test case for a method returning object如何为返回对象的方法编写测试用例
【发布时间】:2012-04-06 00:08:50
【问题描述】:

我有一个返回类型为对象的方法。如何为此创建测试用例?我如何提到结果应该是一个对象?

例如:

public Expression getFilter(String expo)
{
    // do something
    return object;
}

【问题讨论】:

    标签: java object junit testcase


    【解决方案1】:

    试试这样的东西。如果您的函数的返回类型是Object,则将Expression 替换为Object

    //if you are using JUnit4 add in the @Test annotation, JUnit3 works without it.
    //@Test
    public void testGetFilter(){
        try {
            Expression myReturnedObject = getFilter("testString");
            assertNotNull(myReturnedObject); //check if the object is != null
            //check if the returned object is of class Expression.
            assertTrue(true, myReturnedObject instanceof Expression);
        } catch(Exception e){
            // let the test fail, if your function throws an Exception.
            fail("got Exception, i want an Expression");
         }
    }
    

    【讨论】:

      【解决方案2】:

      在您的示例中,返回类型是 Expression?没看懂,能详细点吗?

      该函数甚至无法返回 Expression 以外的任何内容(或派生类型或 null)。所以“检查类型”是没有意义的。

      [TestMethod()]
      public void FooTest()
      {
          MyFoo target = new MyFoo();
          Expression actual = target.getFilter();
      
          Assert.IsNotNull(actual);  //Checks for null
          Assert.IsInstanceOfType(actual, typeof(Expression)); //Ensures type is Expression
      }
      

      我在这里假设 C#;您没有标记您的问题,也没有提及问题中的语言。

      【讨论】:

      • 嗨,我需要 junit 测试用例。我刚刚提到了 Expression 它的实际对象。
      • 所以下次用 'java' 和 'junit' 标记你的问题,并确保示例代码准确地重现或演示了你的问题 ;-) (这次是为你做的)。我认为关键是 instanceof 但我不是 Java 大师 :-) 你可能还想查看 stackoverflow.com/questions/496928/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 2023-03-08
      • 1970-01-01
      • 2015-11-03
      • 2023-02-17
      • 1970-01-01
      相关资源
      最近更新 更多