logo
down
shadow

Net Core: How to Simple Unit Test Repository and Service with Database Rows


Net Core: How to Simple Unit Test Repository and Service with Database Rows

Content Index :

Net Core: How to Simple Unit Test Repository and Service with Database Rows
Tag : chash , By : user179445
Date : November 27 2020, 05:23 PM

it fixes the issue You don't want to create a mock of the DepartmentAppService. You want to create an instance. The method you are testing requires an instance of the real object, not a mock. You want to test the actual object's code, mocks don't run any code but only return fake data.
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(sharedServicesProfile);
        });
        mapper = config.CreateMapper();

var departmentAppService = new DepartmentAppService(departmentRepositoryMock.Object, mapperMock.Object);
AutoMapper.Mapper.Initialize(m => m.AddProfile<YOUR AUTOMAPPER PROFILE>());
AutoMapper.Mapper.AssertConfigurationIsValid();
var options = new DbContextOptionsBuilder<TestContext>()
        .UseInMemoryDatabase(databaseName: "TestDatabase")
        .Options;

var context = new TestContext(options))
context.Department.Add(new Department { DepartmentId = 2, DepartmentCode = "123", DepartmentName = "ABC" });
context.SaveChanges();    

var departmentRepository = new Repository<Department>>(context);
var departmentAppService = new DepartmentAppService(departmentRepository, mapper);

var test = await departmentAppService.GetDepartmentById(5);

Assert.Equal("123", test.DepartmentCode);

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Unit testing, mocking - simple case: Service - Repository


Tag : chash , By : cnemelka
Date : March 29 2020, 07:55 AM
This might help you Personally, I wouldn't care about this. The test should make sure that the code is doing what you intend. It's very hard to test what code is not doing, I wouldn't bother in this case.
The test actually should just look like this:
[Test]
public void GetProduct_GetsProductFromRepository() 
{
   var product = EntityGenerator.Product();

   _productRepositoryMock
     .Setup(pr => pr.GetProduct(product.Id))
     .Returns(product);

   Product returnedProduct = _productService.GetProduct(product.Id);

   Assert.AreSame(product, returnedProduct);
}

How to set up a unit test for spring data with service and repository?


Tag : java , By : eferro
Date : March 29 2020, 07:55 AM
this one helps. I have checked many SO comments and the docs for spring data and unit testing but I cant get this to work and I dont know why its not working. , For a repository bean to be injected,
@Configuration
@WebAppConfiguration
@ComponentScan(basePackages = "com.amanu.csa",
        excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = WebConfig.class))
@EnableMongoRepositories(repositoryImplementationPostfix = "CustomImpl")
class TestConfig {

    @Bean
    Mongo mongo() throws Exception {
        return new MongoClient("localhost")
    }

    @Bean
    MongoDbFactory mongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(mongo(), "csa_test")
    }

    @Bean
    MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate template = new MongoTemplate(mongoDbFactory())
        template.setWriteResultChecking(WriteResultChecking.EXCEPTION)
        return template
    }
}
@ContextConfiguration(classes = TestConfig)
@RunWith(SpringRunner.class)
class OrganizationServiceTest {

    @Autowired
    OrganizationService organizationService

     @Test
    void testRegister() {
        def org = new Organization()
        //...
        organizationService.register(org)
        // ...
    }

How to do a Spring Unit Test of a Service layer that use Repository?


Tag : java , By : user119605
Date : March 29 2020, 07:55 AM
seems to work fine This may be a mildly controversial opinion, but I would focus on unit testing only your converter as there is no other meaningful custom logic in this method.
Looking at the method it does:
// 1 - Create an instance of a Spring class
PageRequest page = new PageRequest(0, total, Sort.Direction.DESC, "Date");
// 2 - Query a Spring Repository with the Spring Class
Page<MessageLog> messages = logRepo.findAll(page);

// 3 - CUSTOM LOGIC to convert result to custom DTO class
List<MessageLogViewDto> messageList = messages.getContent().stream().map(
        message -> convertDto.toMessageLogView(message)).collect(Collectors.toList());

// 4 - Return a Java standard CompleteableFuture 
return CompletableFuture.completedFuture(messageList);
List<MessageLogViewDTO> convertMessageLogsToMessageLogViewDTO(List<MessageLog> messages) {
  return messages.getContent().stream().map(
    message -> convertDto.toMessageLogView(message)).collect(Collectors.toList());
}

EF Core - Simple unit test of repository pattern


Tag : chash , By : jgood
Date : March 29 2020, 07:55 AM
I hope this helps . You can use InMemory database provider in EF Core.
So basically you can do something like this:
var options = new DbContextOptionsBuilder<RouteMiningDataContext>()
    .UseInMemoryDatabase(databaseName: "database_test_name")
    .Options;

using (var context = new RouteMiningDataContext(options))
{
    //your test
}
public RouteMiningDataContext(DbContextOptions<RouteMiningDataContext> : base(options)
    { }
"Server=(localdb)\MSSQLLocalDB;Database=EFProviders.InMemory;Trusted_Connection=True;"

How to unit test a simple repository that contains a dagger injection?


Tag : java , By : druta
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Unit test usually means you test a single component, supplying friendlies / mocks / stubs to test some behavior. There is no need for Dagger in unit tests, so to answer your question you should simply pass your mock to UserRepository.
UserRepository repository = new UserRepository();
repository.mUserWebService = mUserWebService;
public class UserRepository {

  UserWebService mUserWebService;

  @Inject
  public UserRepository(UserWebService userWebService) {
    mUserWebService = userWebService;
  }
}

// and then simply call the constructor...

UserRepository repository = new UserRepository(mUserWebService);
Related Posts Related QUESTIONS :
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • C# XDocument Element/Elements returns null
  • Autofac keyed service with IEnumerable relationship type
  • Installing EntityFramework via NuGet manager
  • Always Check if there is Internet Connection Xamarin forms
  • WCF OneWay service slows down when aspNetCompatibilityEnabled is set to false
  • Can we use JsonRequestBehavior.AllowGet with [HttpPost] attribute?
  • How to customize the Setup wizard with custom forms in Visual Studio setup project
  • C# ASP.NET - Use method from another class to create labels
  • C# List IList or IEnumerable as argument
  • Parsing File with C# And Replace method
  • Losing special unicode characters in encryption (C#)
  • Getting stored procedure returned value instead of row affected
  • How can I construct HTML using NameValuePair in android?
  • Loading a pop up page in ASP.net through a js file
  • How to pass alert or notification message from controller to View?
  • C# to pause, turn on ssas server, backup cube.... how to?
  • How to execute DataTable.Select() for a column of custom class type for a particular element in that C#
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How to convert Word document created from template by OpenXML into MemoryStream?
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • Attempt to invoke virtual method on a null object reference Xamarin LockScreen
  • "The attribute names could not be inferred from bind attribute 'bind-value'" exception in Blazor
  • How to fix ''System.ArgumentException" in c#?
  • C#. Ref returning delegate for ref extension method
  • Swashbuckle Swagger generate an actual guid
  • Trying to make thousands of database calls simultaneously - they stack instead of running concurently
  • run mstest from cmd using testcontainer
  • How to make M:N (many-to-many) relationship where both M and N are the same entities?
  • Consume COM DLL from multiple clients
  • Convert json string response representing UCHAR array to Byte array
  • Why does this LinqPad program produce different results on the second run?
  • ServiceStack how to use MaxLoginAttempts feature
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com