如何验证是否在被测系统(不是模拟系统)上调用了方法 [英] How to verify if method is called on System under test (not a mock)
问题描述
我正在尝试编写一个单元测试,该单元测试需要确认是否调用了一个方法.我正在使用JUnit,Mockito和PowerMock.
I'm trying to write a unit test that needs to confirm if a method is called or not. I'm using JUnit, Mockito and PowerMock.
public class Invoice
{
protected void createInvoice()
{
// random stuff here
markInvoiceAsBilled("57");
}
protected void markInvoiceAsBilled(String code)
{
// marked as billed
}
}
因此,这里我的测试系统是Invoice
.我正在运行此测试:
So, here my system under test is Invoice
. I'm running this test:
public class InvoiceTest
{
@Test
public void testInvoiceMarkedAsBilled()
{
Invoice sut = new Invoice();
Invoice sutSpy = spy(sut);
sut.createInvoice();
// I want to verify that markInvoiceAsBilled() was called
}
}
此示例只是实际代码的示例....
This example is just an example of what the actual code looks like....
我的问题是,mockito表示您只能验证是否在模拟对象上调用了一个方法...但是我不想模拟该对象,因为它是我的测试对象.我知道您可以监视正在测试的对象,所以这是我尝试的方法:
My problem is that mockito says you can only verify if a method is called on a mocked object... but I don't want to mock this object, as it's my object under test. I know that you can spy on the object you're testing, so here's what I tried:
verify(sutSpy).markInvoiceAsBilled("57");
我想做的是不可能的吗?还是我只是以错误的方式去做?
Is what I'm trying to do not possible? Or am I just going about it the wrong way?
谢谢大家:)
推荐答案
我不确定您尝试做的事情是否是解决问题的最佳方法.
I'm not sure if what you are attempting to do is the best way to go about things.
我对验证Invoice.createInvoice()
调用内部私有方法markInvoiceAsBilled()
并不担心-而是测试调用createInvoice()
以您期望的方式更改了Invoice对象的状态-即BILLED
或类似名称.
I wouldn't concern myself with verifying that Invoice.createInvoice()
calls an internal, private method markInvoiceAsBilled()
- instead test that calling createInvoice()
changes the state of the Invoice object in the way you expect - i.e., that status
is now BILLED
or something similar.
换句话说-不要测试createInvoice()
调用了什么方法-测试在调用此方法之后,对象的 state 是您所期望的.
In other words - don't test what methods are called by createInvoice()
- test that after calling this method, the state of the object is what you expect.
这篇关于如何验证是否在被测系统(不是模拟系统)上调用了方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!