我是Java单元测试的新手。 我有以下模型:
export class CartItem {
item: Item;
someVariableWhichIsNotImportant = {};
varA = 12;
constructor(cfg: Partial<CartItem> = {}) {
if (!cfg.item) {
throw new Error('Item is missing');
}
//...some other error conditions
this.item = cfg.item;
//....some other variables
}
}
然后,我非常简单但已损坏的单元测试如下:
import { Item } from './item.model';
import { CartItem } from './cart-item.model';
describe('something to describe', () => {
let a;
const titel = "blah blah";
const ITEM_1 = new Item();
ITEM_1.title = title1
const CART_ITEM = new CartItem();
CART_ITEM.item = ITEM_1;
it('should have a start date of xxx', () => {
expect(ITEM_1.tile).toBe(title1);
});
});
运行测试时,我有Error: Item is missing
。我在做什么错了?
答案 0 :(得分:1)
您需要将依赖项注入new CartItem()
;
代码中CartItem
的构造函数期望cfg: Partial<CartItem>
创建类的实例。
将模拟的cfg
添加到您的CART_ITEM
例如:
const CART_ITEM = new CartItem(mockedCfg);
尝试在初始化时传递这些值,它应该可以工作。