如何检查 Junit 中的三元运算符方法传递的是哪个值?
How to check which value is passing in ternary operator method in Junit?
我是 Junit 的新手,正在尝试为以下场景编写测试用例。
public List<String> transformColumns(String action){
return action.equals("delete"))?
tableInsert("onetwo", false)
:tableInsert("onetwothree", true);
}
如果,我将 action 值作为 transformColumns("delete"), tableInsert("onetwo", false) 方法应该在第二个参数中使用 false 的值调用。 Junit中如何校验被调用方法的参数值?
你可以在你要测试的对象上使用Mockito to verify that some method is called. In this case you can use spy()
,调用transformColumns()
方法并用verify()
检查,确实调用了tableInsert()
方法。单元测试方法可能如下所示:
@Test
public void mockitoTest() {
Foobar mock = Mockito.spy(Foobar.class);
mock.transformColumns("delete");
Mockito.verify(mock).tableInsert(Mockito.anyString(), Mockito.eq(false));
}
此测试将通过,因为调用 transformColumns("delete")
将在内部调用 tableInsert()
方法,第二个参数的值为 false
。如果您更改 transformColumns()
的参数或将预期参数 false
更改为 true
,您将看到此单元测试方法将失败并出现如下错误(表达式 Mockito.eq(true)
用于显示错误):
Argument(s) are different! Wanted:
foobar.tableInsert(<any string>, true);
-> at testing.AllTests.mockitoTest(AllTests.java:14)
Actual invocations have different arguments:
foobar.transformColumns("delete");
-> at testing.AllTests.mockitoTest(AllTests.java:12)
foobar.tableInsert("onetwo", false);
-> at testing.Foobar.transformColumns(Foobar.java:8)
我是 Junit 的新手,正在尝试为以下场景编写测试用例。
public List<String> transformColumns(String action){
return action.equals("delete"))?
tableInsert("onetwo", false)
:tableInsert("onetwothree", true);
}
如果,我将 action 值作为 transformColumns("delete"), tableInsert("onetwo", false) 方法应该在第二个参数中使用 false 的值调用。 Junit中如何校验被调用方法的参数值?
你可以在你要测试的对象上使用Mockito to verify that some method is called. In this case you can use spy()
,调用transformColumns()
方法并用verify()
检查,确实调用了tableInsert()
方法。单元测试方法可能如下所示:
@Test
public void mockitoTest() {
Foobar mock = Mockito.spy(Foobar.class);
mock.transformColumns("delete");
Mockito.verify(mock).tableInsert(Mockito.anyString(), Mockito.eq(false));
}
此测试将通过,因为调用 transformColumns("delete")
将在内部调用 tableInsert()
方法,第二个参数的值为 false
。如果您更改 transformColumns()
的参数或将预期参数 false
更改为 true
,您将看到此单元测试方法将失败并出现如下错误(表达式 Mockito.eq(true)
用于显示错误):
Argument(s) are different! Wanted:
foobar.tableInsert(<any string>, true);
-> at testing.AllTests.mockitoTest(AllTests.java:14)
Actual invocations have different arguments:
foobar.transformColumns("delete");
-> at testing.AllTests.mockitoTest(AllTests.java:12)
foobar.tableInsert("onetwo", false);
-> at testing.Foobar.transformColumns(Foobar.java:8)