Skip to content

How to inject dependency in class #326

@ijalalfrz

Description

@ijalalfrz

i have class to be injected by repositry class with DI, it looks like this:

// handler.py

class Handler: @inject def __init__(self, rating_repo: Provide[Container.repo.rating] = None): self.rating_repo = rating_repo def save_rating(self, cmd: SaveRating): runner_rating = RunnerRating() runner_rating.add_runner(cmd.runner) runner_rating.add_merchant(cmd.childMerchant) runner_rating.add_rating(cmd.rating) self.rating_repo.add(runner_rating) 

then i try to test the class with unittest:

 import unittest from src.container import Container from src.runner_rating.service.handler import Handler from src.runner_rating.domain.commands import SaveRating from src.runner_rating.domain.models import Rating, Runner, ChildMerchant class HandlerTest(unittest.TestCase): def setUp(self): self.container = Container() self.container.config.from_ini('env.dev.ini') self.container.wire(modules=[Handler]) rating = Rating(**{ "value": 5, "tags": [ "ketepatan waktu pengiriman", "kondisi barang", "keramahan pengirim" ] }) runner = Runner(**{ "id": "25b1c252-104c-4ebe-804d-ab6e63007ca1", "employeeNumber": "916452", "name": 'namarunner' }) merchant = ChildMerchant(**{ "id": "96cc8d00-f48f-4731-a477-52dbe82a3e15", "code": "3412409", "mor": "3", "name": "SPBU 3412409", }) self.data = SaveRating(id='tes', runner=runner, rating=rating, childMerchant=merchant) def test_save_rating(self): handler = Handler() handler.save_rating(self.data) 

but the repo_rating is None/ empty? how to do DI in class?
if i remove None default param, the test show error thant Handler class need 1 argument in initializaiton

thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions